1
votes

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

1
error cleared by placing DataRow dtRow = dt.NewRow(); inside for loop - Happy

1 Answers

0
votes

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);
      }
}