如何将DataGridView中选择的行添加到DataTable中

3

我最近开始使用Windows窗体应用程序。在一个数据网格视图DatagridView1中,我正在显示一些来自数据表dt1的数据。

DatagridView1.DataSource=dt1;

我在DatagridView1中添加了一个名为selectRows的列,类型为DataGridViewCheckBoxColumn

我想要将DatagridView1中选中的行添加到另一个数据表中。 我有一个名为btn_Select的按钮,在按钮单击时,我使用以下代码以字符串格式获取选定的行:

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";
                }
            }
       }

但是我想选择整行,而不仅仅是文本。

您可以选择行中的单元格并相应地添加数据...例如,Row.Cells[n],其中n为0、1、2等。 - nitinvertigo
我尝试使用{foreach (DataGridViewCell cell in row.Cells [0])},但它给出了一个错误,“System.Windows.Forms.DataGridViewCell”不包含'GetEnumerator'的公共定义。 - Rocky
2个回答

1
使用 DataBoundItem 属性获取整行数据。使用 DataTable.ImportRow 方法可以将所选行的数据导入到不同的表中。
示例代码:
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);
        }
    }

如何使用DataBoundItem属性获取整行数据。 - Rocky
@Rocky - 请查看示例代码。假设您已经从数据库中填充了数据表,您可以使用DataBoundItem属性访问绑定到整个行的数据。 - Junaith

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接