我有两个DataGirdViews。我想从右侧DataGridView中选择行并将它们传递给左侧的行。
右边有4列。在左侧网格中,我只定义了一个新列,我只想显示此列。这列是正确的列之一,比如专栏[2]。 我被困在这里,不知道如何传递行?
我的代码未完成(可能是错误,未经测试):
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (dgRight.CurrentRow != null)
{
DataRowView currentDataRowView = (DataRowView)dgRight.CurrentRow.DataBoundItem;
foreach (DataGridViewRow row in dgRight.Rows)
{
DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
if (check.Value != null)
{
if ((bool)check.Value)
{
//this row has a checkBox set to true (tick is added)
//add this row to dataTable ...
DataRow myRow = (row.DataBoundItem as DataRowView).Row;
DataRow dr = dt.NewRow();
if (!dt.Columns.Contains("ID"))
{
datatableRight.Columns.Add("ID", typeof(int));
datatableRight.Columns.Add("col1", typeof(string));
datatableRight.Columns.Add("col2", typeof(string));
datatableRight.Columns.Add("col3", typeof(string));
DataColumn[] keyColumns = new DataColumn[1];
keyColumns[0] = datatableRight.Columns["ID"];
datatableRight.PrimaryKey = keyColumns;
}
dr["ID"] = myRow["ID"];
dr["col1"] = myRow["col1"];
dr["col2"] = myRow["col2"];
dr["col3"] = myRow["col3"];
if (!datatableRight.Rows.Contains(dr[0]))
{
datatableRight.Rows.Add(dr);
}
}
}
}
dgLeft.DataSource = datatableRight;
datLeft = datatableRight.Copy();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
感谢。
答案 0 :(得分:1)
简单地使用两个具有相同模式的dataTable来绑定这些网格,然后在DataTables中移动行。
答案 1 :(得分:0)
快速显示使用数据复制列的概念 -
dataGridView2.AutoGenerateColumns = false;
///... assuming that datagridview2 is already created with proper columns
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = dataGridView2.DataSource;
private void btnAdd_Click(object sender, EventArgs e)
{
for (int j = 0; j < this.dataGridView2.Columns.Count; j++)
{
if (dataGridView2.Columns[j].Name == "Description")
{
this.dataGridView1.Columns.Add(this.dataGridView2.Columns[j].Clone() as DataGridViewColumn);
}
}
}