DataGridViewRow到Form

时间:2011-08-11 07:39:00

标签: c# winforms visual-studio-2008 datagridview

我需要将双击行的数据网格中的数据转换为新的表单,我只是潜入了dotnet开发,请指导方法。

2 个答案:

答案 0 :(得分:2)

首先,正如Gapton所说,您需要处理CellDoubleClick事件,在此事件中,您可以使用以下语法获取当前行的单元格值:

object cell1 = dataGrid.Rows[e.RowIndex].Cells[0].Value; 
object cell2 = dataGrid.Rows[e.RowIndex].Cells[2].Value;

其中e.RowIndex是双击的行用户的索引,e.ColumnIndex包含发生此双击的单元格的列索引...

现在,要将值传递给新表单,您可以通过两种不同的方式执行此操作: 1:使用公共属性,比如你有要传递值的Form2,在Form2类中定义你感兴趣的值的属性,如:

public object cell1 { get; set; }
public object cell2 { get; set; }

并在上面的CellDoubleClick中,实例化Form2的新对象,为属性赋值并调用show方法以显示此表单:

private void dataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            object cell1 = dataGrid.Rows[e.RowIndex].Cells[0].Value; 
            object cell2 = dataGrid.Rows[e.RowIndex].Cells[2].Value; 

Form2 form2 = new Form2();
form2.cell1 = cell1;
...
form2.Show();
        } 

2:使用重载的构造函数,为Form2编写一个重载的构造函数,如下所示:

public Form2(object cell1, ...) {
this.cell1 = cell1;
....
InitializeComponent();
}

然后在事件处理程序中:

private void dataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            object cell1 = dataGrid.Rows[e.RowIndex].Cells[0].Value; 
            object cell2 = dataGrid.Rows[e.RowIndex].Cells[2].Value; 

Form2 form2 = new Form2(cell1...);
form2.Show();
        } 

答案 1 :(得分:1)

在“事件”面板中,您可以指定在双击行时调用的函数。在函数中,您可以执行DataGridViewRow.Cells [index] .Value来访问单元格的值,然后将其传递给新表单用于任何目的。

或者,您可以传递整个DataGridViewRow: dataGridView1.CurrentRow将为您提供当前选中的DataGridViewRow。