29 August, 2009

DataSet Details

Filling dataset with data from more than one table
------------------------------------------------------------
To Fill dataset with data from more than one table from database and to
bind that data to datagrid we need following code

1. In .aspx file you need to write

&ltdiv>
&ltasp:datagrid id="grid1" runat="server" autogeneratecolumns="True">

&ltasp:datagrid id="grid2" runat="server" autogeneratecolumns="True">



Here we are specifying 2 datagrids to display data from 2 Tables.

2. In .aspx.cs file

1. First we need to open a connection

SqlConnection newconn = new SqlConnection(“Server=xxx;
InitialCatalog=xxx; UserId=xx;Password=xxx”);
Newconn.open();

In the above statement server= xxx means we are specifying server
name.InitialCatalog means database name from which we want to
retrive data. Userid, password are userid and passwords of user
for sql server.

2. Next we need to specify the sql statements(required operation)

DataAdapter da = new SqlDataAdapter("select * from firsttablensme;
Select * from secondtablename”, newconn)

note: here instead of command object we are directly using
DataAdapter.If you want you can use command object also.

In the above statement we are selecting data from two tables.
Newconn is the connection object.

3. Now, we need to fill the dataset

ds = new DataSet();
da.Fill(ds, “firsttablename”);
da.Fill(ds, “secondtablename”);

Here we are using Fill() method of dataadapter to fill the Dataset.

4. Now to bind this data to datagrid we need following code

grid1.DataSource = ds;
grid1.DataSource = ds.Tables[0];
grid1.DataBind();

grid2.DataSource = ds.Tables[1];
grid2.DataBind();

Here DataSource property represents the datasource of the datagrid and
DataBind() method used to bind data to the datagrid.

Note: you can also use caption property of datagrid to specify the table caption
Ex: grid1.caption = “xxx”
here Xxx represents cation for the table displayed by datagrid.

No comments: