views:

2031

answers:

3

I have a grid view which contains 10 rows and 3 columns.. Now i want to loop through all rows and all columns of the gridview and want to add them to a datatable..

  DataRow row;
  int rowscount = gv.Rows.Count;
    int columnscount = gv.Columns.Count;
    for (int i = 0; i < rowscount; i++)
    {
        for (int j = 0; j < columnscount; j++)
        {
            row = empTable.NewRow();
            row["a"] = gv.Rows[i][column1].Tostring();
            row["b"] = gv.Rows[i][column2].ToString();
            MynewDatatable.Rows.Add(row);
        }
    }    

gv - my gridview

Now my question is , Can i get the value of all columns of all rows in gv to my new datatable.. I dont know whether my loop is correct or not... I am using this datatable for a bulkcopy function...

A: 

Your loop is incorrect, all lists start at 0. But you start at 1 when looping through the columns.

Bobby
+2  A: 
  • Your code above is creating a new Row for every cell in the GridView.
  • within each row of the GridView your code is assigning every value in the row to the same column, Emp_Name.

Corrected, I think:

int rowscount = gv.Rows.Count;
int columnscount = gv.Columns.Count;
for (int i = 0; i < rowscount; i++)
{
    // Create the row outside the inner loop, only want a new table row for each GridView row
    DataRow row = empTable.NewRow();
    for (int j = 1; j < columnscount; j++)
    {
        // Referencing the column in the new row by number, starting from 0.
        row[j - 1] = gv.Rows[i][j].Tostring();
    }
    MynewDatatable.Rows.Add(row);
}

EDIT: You've been editing the source in your question, so my answer may grow out-of-date. :)

JMD
@JMD row[j - 1] = gv.Rows[i][j].Tostring(); when i use this it says error Cannot apply indexing with [] to an expression of type 'System.Web.UI.WebControls.GridViewRow'
Pandiya Chendur
That message sounds like it is referring to the right-hand side of the statement, `gv.Rows[i][j]`, which was your original code (which is now gone from your question.) The left-hand side of the statement in my answer is `row[j - 1]`, which is the `DataRow` object, not the error message's `GridViewRow`. (*As an aside, in future you might consider editing your code with comments rather than deleting/replacing code, so that readers can keep track of what you originally asked.*) :)
JMD
A: 

The JMD answer is correct, but depending on your use-case, maybe databinding the DataSource of your grid view to your DataTable would be a better approach.

Rafa Castaneda