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

3 Comments

  • great help…

  • Hi!

    Can you include the full code sample?

  • thanks. but i think code behind is right

    dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

Leave a comment

Check these Out!

Subscribe and get the latest posts in your inbox by entering your email address below