Tehrik-e-Insaaf

Earn 600$ by Clicking on each Ad

GoWellUp.com

Wednesday, October 22, 2008

How to fill the datagrid with the data from database using datasets

1. Make connection String and selection statement
SqlConnection conn = new SqlConnection(@"Data Source=192.125.5.1;Initial Catalog=Test;User ID=sa;Password=sa;");
string getCommand = @"select * from dbo.compDetails";

2. Declare the object of command & give the respective parameters
//give selection statement
SqlCommand cmd = new SqlCommand(getCommand);
//give the command type
cmd.CommandType = CommandType.Text;
//give connection object
cmd.Connection = conn;

3. Declare the object of SqlDataAdpater & give command object
SqlDataAdapter da = new SqlDataAdapter(cmd);

4. Declare the object of dataset as container of data
DataSet ds = new DataSet();

5. Open the connection
conn.Open();

6. Fill the object of data Adapter with dataset object
da.Fill(ds, "dbo.complaints");

7. Provide the dataset object as a source to dataGrid
this.dataGrid1.DataSource = ds.Tables[0];

8. Close the connection
conn.Close();


Example:

public void getData()
{
SqlConnection conn = new SqlConnection(@"Data Source=192.125.5.1;Initial Catalog=Test;User ID=lrmis;Password=lrmis;");
string getCommand = @"select * from dbo.compDetails";
SqlCommand cmd = new SqlCommand(getCommand);
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds, "dbo.complaints");
this.dataGrid1.DataSource = ds.Tables[0];
conn.Close();
}

No comments: