Reputation: 287
i am working with Desktop Application and i am trying to create a datatable from a datagridview. but i only want to add those rows when checkbox is selected or checked. currently i created a datatable from a whole datagridview like this.
DataTable tbl = (DataTable)dataGridView1.DataSource;
I have added a checkbox coloumn inside datagridview.. so please guide me how to add selected rows to a new datatable
Thanks.. Here is the new code Update
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value) == true)
{
DataRow dr0 = tbl.NewRow();
dr0["ID"] = dataGridView1.Rows[i].Cells["ID"].Value;
dr0["BikeCC"] = dataGridView1.Rows[i].Cells["BikeCC"].Value.ToString();
dr0["ChassisModel"] = dataGridView1.Rows[i].Cells["ChassisModel"].Value.ToString();
dr0["BikeCC"] = dataGridView1.Rows[i].Cells["BikeCC"].Value.ToString();
dr0["ChassisModel"] = dataGridView1.Rows[i].Cells["Chassismodel"].Value.ToString();
tbl.Rows.Add(dr0);
}
}
objMdl.RecordTable = tbl;
This is the way i could find to add selected rows into a new datatable... it is lenghty but i am still facing little issues. which i will post in a bit for your look.
Upvotes: 0
Views: 4952
Reputation: 63327
Suppose your checkbox column is named yourCheckBoxColumn:
DataTable tbl = ((DataTable)dataGridView1.DataSource).Clone();//Clone structure first
var rows = dataGridView1.Rows.OfType<DataGridViewRow>()
.Where(r=>Convert.ToBoolean(r.Cells["yourCheckBoxColumn"].Value))
.Select(r=>((DataRowView)r.DataBoundItem).Row);
foreach(var row in rows)
tbl.ImportRow(row);
Upvotes: 1