Reputation: 33
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.
Upvotes: 3
Views: 7537
Reputation: 4100
I think you are looking for this. This is exactly what you want.
DataGridView checkbox column - value and functionality
Upvotes: 0
Reputation: 3388
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);
}
}
Upvotes: 1