【发布时间】:2017-11-23 11:18:30
【问题描述】:
我在一个表单中有一个dataGridView1、dataGridView2 和一个ButtonAdd。
用户将:
1- 选择任何一个“单元格”或“整行”。
2-选择多行
然后:
单击按钮时,所选数据将从 dataGridView1 移动到 dataGridView2。这就是我需要做的。
我的尝试:
经过多次搜索,我尝试了这个解决方案,几乎完成了,但有一个小问题我无法处理:
完整代码:
private const string strconneciton = @"YourConnectionString";
SqlConnection con = new SqlConnection(strconneciton);
SqlCommand cmd = new SqlCommand();
DataTable dataTable;
private void loadDataIntoGridView1()
{
try
{
con.Open();
cmd.CommandText = "SELECT id, accNum, accName FROM Employees";
cmd.Connection = con;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
dataTable = new DataTable();
adapter.Fill(dataTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dataTable;
dataGridView1.DataSource = bSource;
//i don't know if this line is useful...
dataGridView2.DataSource = dataTable.Clone();
adapter.Update(dataTable);
con.Close();
}
catch (Exception ed)
{
con.Close();
MessageBox.Show(ed.Message);
}
}//end loadDataIntoGridView1
private void buttonSend_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedCells.Count > 0)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
{
//this should add the rows that is selected from dataGridView1 and,
//pass it to dataGridView2
var currentRow = ((DataRowView)dataGridView1.CurrentRow.DataBoundItem).Row;
((DataTable)dataGridView2.DataSource).ImportRow(currentRow);
//this will remove the rows you have selected from dataGridView1
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}//end if
}//end foreach
}//end if
}//end button click
让我们调试:
在开始之前注意一件事:
- 删除行(多行或单行)的方法在所有情况下都可以正常工作。
- 添加到 DGV2 的方法是个问题,我是从 here 那里得到的……它在选择单行而不是多行时工作正常。
1-如果您选择了一个单元格/行,它将成功添加和删除。
2- 如果您选择了多行,比如说第一行和第二行,它会添加第二行和第三行,然后肯定会删除它们,但只添加一个.. 为什么?!
因为这里
var currentRow = ((DataRowView)dataGridView1.CurrentRow.DataBoundItem).Row;
((DataTable)dataGridView2.DataSource).ImportRow(currentRow);
获取DGV1中现有行的当前索引,并迭代选择行数并将它们添加到DGV2。
截图:
应该怎么做才能解决这个问题?
【问题讨论】:
-
你试过insert?
-
不,我认为,如果您有描述“插入”的方法来解决我的问题,我将不胜感激。
标签: c# datagridview datagrid datagridviewcolumn datagridviewrow