GridView values to DataTable

| December 11, 2010 | 0 Comments

Sometime you need GridView’s values to DataTable for programming requirement. So this article tries to help you achieve that objective.

We have simply declared DataTable and added columns of matching types to it(matching with columns in sql database). And then used foreach loop for each GridViewRow in GridView’s rows to add GridView row to DataTable’s rows. And finally added those rows to DataTable. Check out code snippet for .aspx page declaration and second one for .aspx.cs declaration.

Code Snippet in .aspx

<asp:<span class="hiddenSpellError">GridView ID="GridView1" runat="server" DataSourceID="SqlSource">
</asp:GridView>
<asp:<span class="hiddenSpellError">SqlDataSource ID="SqlSource" runat="server" SelectCommand="SELECT * FROM Test"
ConnectionString="<%$ ConnectionStrings:conString  %>">
<asp:Button ID="btnGetData" runat="Server" Text="Get Data" OnClick="btnGetData_Click" />


Code Snippet in .aspx.cs

protected void btnGetData_Click(object sender, EventArgs e)
    {
        // CREATING NEW DATATABLE & COLUMNS
        DataTable dt = new DataTable();
        DataRow dr;
        dt.Columns.Add("SlNo", typeof(Int32));
        dt.Columns.Add("Name", typeof(String));
if (GridView1.DataSource==null)
{
foreach(GridViewRow gvr in GridView1.Rows)
{
dr = dt.NewRow();

for (int i = 0; i < gvr.Cells.Count; i++)
{
dr[i] = gvr.Cells[i].Text;
}

dt.Rows.Add(dr);
}

// CHECKING IF DATATABLE CONTAINS ROWS OR NOT
int rows = dt.Rows.Count;
int column = dt.Columns.Count;
Response.Write("Total Columns:" + column.ToString() + "and Rows: " + rows.ToString());
}
}

Category: Asp.Net

Leave a Reply

Sex Chat Live Jasmin WP-Clear 3.0 Theme
%d bloggers like this: