简体   繁体   中英

Add Datagridview Rows to Datatable when Checkbox is Checked in C#

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM