loop through all rows and columns of a gridview using C#

c#, for-loop, gridview

Solution

- 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. :)

Problem

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...

Original source