数据网格、窗体和委托。






4.41/5 (15投票s)
2004年2月18日
2分钟阅读

63696

3045
本文档描述了如何使用委托从一个窗体中的数据网格传递数据,到另一个窗体中的一组控件。
引言
本文将解释如何在 Windows 窗体中的数据网格上选择一行,并使用委托在另一个 Windows 窗体中填充控件。本文中的示例源于尝试找到在两个独立的窗体之间传递数据的一种方法,这两个窗体位于我创建的自定义插件中。这两个窗体都没有父窗体,因此我无法使用它们作为两个窗体之间的桥梁。
背景
有很多文章描述了委托是什么以及如何设置它们,我将把这部分留给读者,并直接进入代码。
使用代码
此示例中的代码包含一个位于 FormBottom
中的数据网格,以及一组位于 FormTop
中的控件。通过从 FormBottom
中的数据网格中选择一行,您可以使用委托自动填充 FormTop
中的控件。明白了吗?请继续阅读。
在 FormBottom.cs 中,我们定义我们的委托。
public delegate void CustomRowHandler(
object sender, CustomRowEventArgs e);
以及事件处理程序,该处理程序定义为 static
。
public static event CustomRowHandler CustomRow;
CustomRowEventArgs
类。传递的参数是 DataSet
、DataGrid
和所选的 Row
。
public class CustomRowEventArgs : EventArgs
{
DataSet dataSet;
DataGrid grid;
int row;
public CustomRowEventArgs(
DataSet DSet,DataGrid Grid,int Row)
{
grid = Grid;
row = Row;
dataSet = DSet;
}
public DataSet DSet
{
get { return dataSet; }
}
public DataGrid Grid
{
get { return grid; }
}
public int Row
{
get { return row; }
}
}
我们在窗体加载时初始化数据网格。有关 BindFamousPeople()
的更多信息,请参阅项目示例代码。DataGridTableStyle
用于获取 DataGrid
的 CurrentRowIndex
。我们只需将 DataGridTableStyle
传递给 DataGrid
,然后在 MouseUp
例程中使用它来获取当前行。
private void FormBottom_Load(
object sender, System.EventArgs e)
{
BindFamousPeople();
dgts = new DataGridTableStyle();
dgts.MappingName = "People";
dataGrid1.TableStyles.Add(dgts);
}
我们将 MouseUp
事件绑定到网格,并获取所选的当前行。当触发 MouseUp
事件时,CustomRow
将 DataSet
、DataGrid
和 currentRowIndex
传递给 FormTop.cs。
public void dataGrid_MouseUp(object sender,
System.Windows.Forms.MouseEventArgs e)
{
int rowIndex = dgts.DataGrid.CurrentRowIndex;
if (CustomRow != null)
{
CustomRow(this, new CustomRowEventArgs(
dataSet1,dataGrid1,rowIndex));
}
在 FormTop.cs 中,我们包含以下代码。通过使用委托,当 FormBottom.cs 中的 mouseUp
事件触发时,将调用 customHander_CustomRow
函数。请参阅上面的 mouseUp
事件。
FormBottom.CustomRow += new DelegateExample.CustomRowHandler(
customHandler_CustomRow);
在 FormTop.cs 中完成所有工作的 customHandler
。
private void customHandler_CustomRow(object sender,
DelegateExample.CustomRowEventArgs e)
{
DataSet dSet = e.DSet;
DataGrid grid = e.Grid;
int row = e.Row;
textBox2.Text = grid[e.Row,0].ToString();
textBox3.Text = grid[e.Row,1].ToString();
textBox4.Text = grid[e.Row,2].ToString();
}
结论
就是这样。我保持源代码非常简单,因此您应该能够轻松地了解正在发生的事情。文章的项目文件和源代码已提供在上方。