将数据表复制到数据网格,而不将它们绑定在一起



我的应用程序中有两个数据网格(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中删除项目。目前,数据表dt绑定到dataGridView2,添加项目后我无法清除它,因为它还清除了dataGridView2

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

您可以使用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;

最新更新