Happy Happy - 2 months ago 12
C# Question

How to store data grid into datatable?

I need to store datagridview selected rows into datatable in single columns like below

DataGridView

user1 user2 user3
ram sam ravi


DataTable

values
ram
sam
ravi


I tried below code

DataTable dt = new DataTable();
dt.Columns.Add("values",typeof(string));

foreach (DataGridViewRow gridRow in dataGridView_settings.Rows)
{
DataRow dtRow = dt.NewRow();

for (int i = 0; i < dataGridView_settings.Columns.Count; i++)
{
dtRow[0] = gridRow.Cells[i].Value;
dt.Rows.Add(dtRow);
}
}


Problem is its adding only one row in the datatable then showing error "This row already belongs to this table."

Answer

You should move the DataRow creation to the inner for

DataTable dt = new DataTable();
dt.Columns.Add("values",typeof(string));
foreach (DataGridViewRow gridRow in dataGridView_settings.Rows)
{
      for (int i = 0; i < dataGridView_settings.Columns.Count; i++)
      {
          DataRow dtRow = dt.NewRow();
          dtRow[0] = gridRow.Cells[i].Value;
          dt.Rows.Add(dtRow);
      }
}