3

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.

Junaith
  • 3,298
  • 24
  • 34
Rocky
  • 33
  • 1
  • 4
  • you can select individual cells in a row and add data accordingly...for e.g. Row.Cells[n] where n is 0,1,2 etc – nitinvertigo Jan 31 '14 at 10:55
  • 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 Jan 31 '14 at 11:05

2 Answers2

1

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);
        }
    }
Junaith
  • 3,298
  • 24
  • 34
  • How I can Use the DataBoundItem property to get the data in the entire row. – Rocky Jan 31 '14 at 11:36
  • @Rocky - see the sample code. Assuming you filled your datatable from an database, you can access the data bound to the entire row using DataBoundItem property. – Junaith Jan 31 '14 at 11:42
0

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

DataGridView checkbox column - value and functionality

Community
  • 1
  • 1
Kamran
  • 4,010
  • 14
  • 60
  • 112