Get data from an SQLDataSource to a DataTable and Bind Grid

This week, I needed to bind a gridview to and SQLDataSource. The only problem is that I need to include extra rows. How to do this? First I removed the binding code to bind the grid directly from HTML (in gridview remove the DataSourceID attribute).

Then I wanted to get the data from the SQL Data source and convert to a data table to insert and update the table as needed. Next is the code to get the data…

DataView dv = new DataView();
DataTable dt = new DataTable();
dv = mySQLDataSource.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();

To insert new rows in the data table

DataRow row = dt.NewRow();
dt["FieldName1"] = "Field 1";
dt["FieldName2"] = 9;
dt.Rows.Add(row);

Finally, to bind the datatable to a gridview, use the next code:

gridView1.DataSource = dt;
gridView1.DataBind();

Hope this helps 😉 Happy Binding

References: here

Advertisements

One thought on “Get data from an SQLDataSource to a DataTable and Bind Grid

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s