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

Categories

3 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *