0

I am attempting to copy datagridview rows to another datagridview when checkboxcolumn is checked. I am loading datagridview1 from treeview when child node is selected. However, when I select another childnode, the previous checkedbox disappears

 private void BtnAdd_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Product Name");
        dt.Columns.Add("Qty");
        dt.Columns.Add("Unit Price");

        foreach (DataGridViewRow row in dgvSelect1.Rows)
        {
           bool isSelected = Convert.ToBoolean(row.Cells["checkBoxColumn"].Value);
            if (isSelected)
                {
               dt.Rows.Add(row.Cells[2].Value);
                }
                dgvSelect2.DataSource = dt;

1 Answers1

0

Heres your Code snippet

In your main class:

private DataTable dt;

In the constructor for the main class:

dt = new DataTable();
dt.Columns.Add("Product Name");
dt.Columns.Add("Qty");
dt.Columns.Add("UnitPrice");
dgvSelect2.DataSource = dt;

Setting dt as DataSource for the DataGrid links the content of the DataTable to the DataGrid so you have to do it just once.

In button click:

dt.Clear();
foreach(var row in dgvSelect1.Rows)
{   
   if ((row.Collumns["checkBoxColumn"].Content as CheckBox).IsChecked)
   {
      var newRow = dt.NewRow();
      newRow["Product Name"] = row["Product Name"];
      /*yadayada*/
      dt.Rows.Add(newRow);
   }
}

Let the data grid create the new row so that the columns are defined so that you just have to fill them individually, and then add it to the DataTable which will then sync to the DataGrid.

Prophet Lamb
  • 530
  • 3
  • 17
  • I am getting errors by running it this way. 'object' does not contain a definition for 'Cells' and Cannot apply indexing with[] to an expression of type 'object'.Errors are on (row.Cells) and row["Product Name"] – Jmtd8001 Sep 19 '19 at 15:26