我需要从datagrid中为双击的行获取数据到一个新的表单中,我刚刚深入到dotnet开发中,请指导我怎么做。
发布于 2011-08-11 16:14:36
首先,正如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();
} 发布于 2011-08-11 15:43:18
在Events面板中,您可以在双击一行时指定要调用的函数。在该函数中,您可以执行DataGridViewRow.Cellsindex.Value来访问单元格的值,然后将其传递给一个新的表单。
或者,您可以传递整个DataGridViewRow: dataGridView1.CurrentRow将为您提供当前选择的DataGridViewRow。
https://stackoverflow.com/questions/7022429
复制相似问题