【问题标题】:Copy Data Table to a Data Grid without binding them together将数据表复制到数据网格而不将它们绑定在一起
【发布时间】:2012-07-30 20:59:55
【问题描述】:

我的应用程序中有两个数据网格(dataGridView1dataGridView2)。我正在将选定的项目从dataGridView1 移动到dataGridView2。以下是我目前的做法:

DataTable dt = new DataTable("dt");
DataTable id = new DataTable("id");
try
{
    if (dataGridView1.Rows.Count > 0)
    {
        for (int i = 0; i < dataGridView1.Rows.Count - 0; i++)
        {
            if (dataGridView1.Rows[i].Cells[0].Value != null)
            {
                DataRow row;
                DataRow idRow;
                row = dt.NewRow();
                idRow = id.NewRow();
                idRow["id"] = dataGridView1.Rows[i].Cells[1].Value.ToString();
                row["id"] = dataGridView1.Rows[i].Cells[1].Value.ToString();
                row["Link Name"] = dataGridView1.Rows[i].Cells[2].Value.ToString();
                dt.Rows.Add(row);
                id.Rows.Add(idRow);
            }
        }
    dataGridView2.DataSource = dt;
}

但是,我还需要能够从dataGridView2 中删除项目。目前,DataTable dt 绑定到dataGridView2,添加项目后我无法清除它,因为它也会清除dataGridView2

基本上,我的问题是,有没有办法在不使用datagrid.DataSource 的情况下将数据表的内容添加到数据网格?

【问题讨论】:

    标签: c# datagridview datatable


    【解决方案1】:

    您可以使用dataGridView2.Rows.Add 函数手动添加每一行。另外,我通常使用dataGridView2.Row(n).Tag 来保存该行数据的实际来源。

    int n = dataGridView2.Rows.Add();
    DataGridViewRow newRow = dataGridView2.Rows[n]; 
    newRow.Cells[0].Value  = "ABC";
    newRow.Cells[1].Value  = 123;
    newRow.Tag = row;
    

    【讨论】:

      猜你喜欢
      • 2021-09-24
      • 2011-01-31
      • 2017-05-14
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多