Hi
I have below Gridview. How to convert it into datatable.
Code
Thanks
Hi
I have below Gridview. How to convert it into datatable.
Thanks
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Vishal YelveRank #178 · 13.6K reputationPosted Apr 30, 2023, 4:07 AM EDT
Try this
DataTable GetDataTable(GridView dtg)
{
DataTable dt = new DataTable();
// add the columns to the datatable
if (dtg.HeaderRow != null)
{
for (int i = 0; i < dtg.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(dtg.HeaderRow.Cells[i].Text);
}
}
// add each of the data rows to the table
foreach (GridViewRow row in dtg.Rows)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text.Replace(" ", "");
}
dt.Rows.Add(dr);
}
return dt;
}
Amit MohantyRank #112 · 20K reputationPosted May 1, 2023, 12:37 AM EDT
To convert the GridView data into a DataTable, you can use the following code:
DataTable dt = new DataTable(); foreach (TableCell cell in grdPlanning.HeaderRow.Cells) { dt.Columns.Add(cell.Text); } foreach (GridViewRow row in grdPlanning.Rows) { DataRow dr = dt.NewRow(); for (int i = 0; i < row.Cells.Count; i++) { dr[i] = row.Cells[i].Text; } dt.Rows.Add(dr); }Naimish MakwanaRank #324 · 7.7K reputationPosted May 1, 2023, 12:52 AM EDT
Try this:
DataTable dt = new DataTable(); // Bind the GridView data to a DataSource IEnumerable data = grdPlanning.DataSource as IEnumerable; if (data != null) { // Convert the DataSource to a DataTable dt = data.Cast().ToTable(); }Thanks
Aman GuptaRank #193 · 12.4K reputationPosted Apr 30, 2023, 11:08 PM EDT
Hello,
You should refer this link, here we have provided the solution in different programming languages.
https://www.codingvila.com/2019/03/convert-gridview-to-datatable-in-c-sharp-and-vb.html?m=1