3
votes

I started working with Windows Form Application recently. In a datagridview DatagridView1 I am displaying some data from a datatable dt1.

DatagridView1.DataSource=dt1;

I have added a column in DatagridView1 named selectRows of type DataGridViewCheckBoxColumn.

I want to add the selected rows of the DatagridView1 to another datatable. I have a button btn_Select, On button click I am getting the selected rows in a string format using following code:

private void btn_Select_Click(object sender, EventArgs e)
        {


            string data = string.Empty;
            foreach (DataGridViewRow row in DatagridView1.Rows)
            {
                if (row.Cells[0].Value != null &&
                       Convert.ToBoolean(row.Cells[0].Value) == true)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.OwningColumn.Index != 0)
                        {


                            data += (cell.Value + " "); // do some thing
                        }
                    }
                    data += "\n";
                }
            }
       }

But I want to select the whole row, not just text.

2
you can select individual cells in a row and add data accordingly...for e.g. Row.Cells[n] where n is 0,1,2 etcnitinvertigo
I tried to use {foreach (DataGridViewCell cell in row.Cells[0])} but its giving me error, 'System.Windows.Forms.DataGridViewCell' does not contain a public definition for 'GetEnumerator'Rocky

2 Answers

1
votes

Use the DataBoundItem property to get the data in the entire row. With DataTable.ImportRow method you can import the selected rows data into a different table.

Sample Code:

DataRow datarow = null;
DataTable dt = new DataTable();
foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if(Convert.ToBoolean(row.Cells[CheckBoxColumn1.Name].Value) == true)
        {
        datarow = ((DataRowView)row.DataBoundItem).Row;
        dt.ImportRow(datarow);
        }
    }
0
votes

I think you are looking for this. This is exactly what you want.

DataGridView checkbox column - value and functionality