我有两个 DataGirdViews。我想从右侧 DataGridView 中选择行并将它们传递给左侧。
右边有 4 列。在左侧网格中,我只定义了一个新列,我只想显示这一列。此列是右侧的列之一,例如 column[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);
}
}
谢谢。