ACP
ACP

Reputation: 35268

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

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

Upvotes: 2

Views: 43087

Answers (4)

sandeep
sandeep

Reputation: 1

Try this code:

        foreach (DataGridViewRow row in dataGridView1.SelectedRows)
        {
            string selectedempid = dataGridView1.SelectedRows[0].Cells["Deptno"].Value.ToString();
            {
                SqlCommand cmd = new SqlCommand("delete from Test_dept where Deptno=" + selectedempid, con);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                MessageBox.Show("deleted");

            }
        }

Upvotes: 0

Rafa Castaneda
Rafa Castaneda

Reputation: 832

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.

Upvotes: 0

JMD
JMD

Reputation: 7377

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

Upvotes: 5

Bobby
Bobby

Reputation: 11576

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

Upvotes: 0

Related Questions