Reputation:
I have two DataGirdViews. I want to select rows from right DataGridView and pass them to the left one.
The right one has 4 columns. In the left grid, I only defined one new column and I want to display this column only. This column is one of columns of the right one, say column[2]. I am stuck here, not sure how to pass the rows?
My incompleted code(maybe error, untested):
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);
}
}
Thanks.
Upvotes: 1
Views: 1427
Reputation: 4866
A quick way to show the concept of copying columns with data -
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);
}
}
}
Upvotes: 0
Reputation: 1057
Simple use two dataTables with same schema to bind these grids, then Move the rows in DataTables.
Check this out sample project. http://www.zumodrive.com/share/ge0nZmRkMz
Upvotes: 1