我在Windows窗体中有一个datagridview,假设它是具有固定列(SAY ID,NAME,AGE)的datagridview1,并且在cellBeginEdit的第一列(即ID)中,我打开了另一个包含datagridview的窗体数据,比如说datagridview2,它也有很多列,例如ID,JOB,NAME,AGE,TYPE。
我想在datagridview2中选择多行,并在输入时将所有选定的行从datagridview2传递到特定列中的datagridview1。
我尝试了很多事情,但是都没有成功。 这是我的代码
从第一种形式开始-datagridview1 CellBeginEdit:
private void dataGridView1_CellBeginEdit(对象发送者, DataGridViewCellCancelEventArgs e)
{
dr = dataGridView1.Rows[e.RowIndex];
if (e.ColumnIndex == dr.Cells["grid_bill"].ColumnIndex)
{
if (dr.Cells["grid_module"].Value.ToString().Equals("SALES"))
{
var form = new frmSalesInvoiceMaster(); //i am calling frmSalesInvoiceMaster where on load i have provided datatable as a datasource to datagridview
form.ShowDialog();
}
}
}
image of my datagridview , it contains 2 datagridview AND both are in differenct forms
表格2,即frmSalesInvoiceMaster
这里是我想要的,用户可以从表单2的datagridview中选择多个行,而我想从表单2的datagridview中获取多个选定的行并隐藏此表单2,并在表单1的datagridview1中显示form2的所有选定行在特定列中。
答案 0 :(得分:1)
假设您在表单1上具有事件dataGridView1_CellBeginEdit:
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if(e.ColumnIndex == 0)
{
Form2 f = new Form2();
var result = f.ShowDialog();
if(result == DialogResult.OK)
{
List<Person> selection = new List<Person>();
f.GetSelection(selection);
BindingSource bs = new BindingSource();
bs.DataSource = selection;
dataGridView1.DataSource = bs;
}
f.Dispose();
}
}
现在,首先,我检查是否已编辑列是第一个(ID)-如果您不在乎,则不必这样做。
接下来,我创建form2并以模态显示它。如果用户在form2上单击“确定”按钮,它将返回DialogResult.OK。
接下来,我创建一个记录列表,该记录列表将与来自form2-> GetSelection的选择一起馈入。
选择后,可以用它填充dataGridView。在这里,我正在使用BindingSource-您还可以做其他事情。
现在是form2:
首先,我加载一些数据:
void LoadData()
{
List<Person> data = new List<Person>();
Person p = new Person { Id = 1, Age = 20, Job = "Consultant", Name = "John" };
Person p2 = new Person { Id = 2, Age = 22, Job = "Programmer", Name = "Steven" };
Person p3 = new Person { Id = 3, Age = 22, Job = "Manager", Name = "Alice" };
Person p4 = new Person { Id = 4, Age = 30, Job = "Analytic", Name = "Mark" };
Person p5 = new Person { Id = 5, Age = 32, Job = "Analytic", Name = "Gregory" };
Person p6 = new Person { Id = 6, Age = 32, Job = "Tester", Name = "Hugh" };
data.Add(p);
data.Add(p2);
data.Add(p3);
data.Add(p4);
data.Add(p5);
data.Add(p6);
bs = new BindingSource();
bs.DataSource = data;
dataGridView1.DataSource = bs;
}
最有趣的方法是GetSelection,它非常简单:
public void GetSelection(List<Person> result)
{
var rows = dataGridView1.SelectedRows;
for(int i = 0; i < rows.Count; i++)
{
Person p = rows[i].DataBoundItem as Person;
if (p != null)
result.Add(p);
}
}
当然不要忘记添加将DialogResult设置为OK的OKButton。