0

我正在使用桌面应用程序,我正在尝试从 datagridview 创建一个数据表。但我只想在选中或选中复选框时添加这些行。目前我像这样从整个datagridview创建了一个数据表。

DataTable tbl = (DataTable)dataGridView1.DataSource;

我在 datagridview 中添加了一个复选框列。所以请指导我如何将选定的行添加到新的数据表中

谢谢..这是新的代码更新

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;

这是我可以找到将选定行添加到新数据表中的方式......它很长,但我仍然面临一些小问题。我会张贴一点供你看。

4

1 回答 1

1

假设您的复选框列名为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);
于 2013-09-18T06:46:36.413 回答