I have a GridView that I am trying to convert to a DataTable. I cannot use the GridView’s DataSource for this DataTable. I’ve found the method below to be the most common way most use to tackle this task, but for some reason, the below method keeps throwing an IndexOutOfRangeException of “Cannot find column 0”. Here’s the code:
DataSet ds = new DataSet("Student"); DataTable dt = new DataTable(String.Format("{0}For{1}", gv.ID.Substring(2, gv.ID.Length - 2), year)); for (int j = 0; j < gv.Rows.Count; j++) { DataRow dr; GridViewRow row = gv.Rows[j]; dr = dt.NewRow(); for (int i = 0; i < row.Cells.Count; i++) { dr[i] = row.Cells[i].Text; //***EXCEPTION IS THROWN HERE*** } dt.Rows.Add(dr); } ds.Tables.Add(dt);
There are 18 cells per row.
Thanks in advance for any help.
Solution
I took CptSupermrkt’s advice and implemented this code just before the first “for” loop, and the method continued w/o throwing the exception:
DataColumn dc;
foreach (var item in gv.Columns)
{
dc = new DataColumn(item.ToString());
dt.Columns.Add(dc);
}
The DataTable you’ve defined does not have any columns defined as well, so the row that you get from dt.NewRow() has no columns. Therefore trying to access the index of columns won’t work.
I would think you need the DataTable you’re creating to have the same columns as your GridView.
Then, when you create use NewRow() on the DataTable, the row will have the columns and you can access them as you try to do in the rest of your code.