日期:2014-05-18  浏览次数:20969 次

【Winform窗体间传值利用自定义事件产生的疑问,望各位帮忙分析】
目的:
        Form1中的右键菜单点击修改过后,需要将Form1中列表的id值和其它一些属性传到Form2

方法:采用自定义事件的方法

疑问:
        我是一新手,对事件机制、变量生存周期不是很清楚,请各位帮忙分析问题出在哪里,谢谢~~~~

偶的代码:
1、定义一委托
      public   delegate   void   ActionEventHandle   (FrmChangeArgs   e);
2、定义的事件参数
public   class   FrmChangeArgs:System.EventArgs
{
public   FrmChangeArgs(int   index)
{
_index=index;
}

private   int   _index;
public   int   Index
{
get
{
return   _index;
}
set
{
_index=value;
}
}
3、Form1中的代码
  //定义事件      
  public   event   ActionEventHandle   frmLostFocus;
  protected   virtual   void   OnfrmLostFocus(FrmChangeArgs   e)
  {
      if   (frmLostFocus!=null)
frmLostFocus(e);
    }
//在右键菜单修改处调用
private   void   menuItem2_Click(object   sender,   EventArgs   e)
{
string   index=this.dataGrid1[this.dataGrid1.CurrentRowIndex,0].ToString();
FrmChangeArgs   arg=new   FrmChangeArgs(Convert.ToInt16(index));
OnfrmLostFocus(arg);
Form2   frmChild=new   Form2   ();
frmChild.Owner   =   this;
frmChild.ShowDialog();
...
}
4、Form2的代码
private   void   Form2_Load(object   sender,   EventArgs   e)
{
//注册事件
Form1   parentFrm=(Form1)this.Owner;
parentFrm.frmLostFocus   +=   new   ActionEventHandle(Form1_frmLostFocus);
if   (index!=-1)   //其中index是该页面私有成员,初始值为-1
{
    //说明是修改页面进入
    InitData();
}
...
}
private   void   Form1_frmLostFocus(   FrmChangeArgs   e)
{
index=e.Index   ;
}

我在跟踪时候发现:
    A)在form2中,我的index始终是-1
    B)在FORM1中,我发现进入OnfrmLostFocus,frmLostFocus总是为空

请各位高手给予分析,谢谢~~~

------解决方案--------------------
OnfrmLostFocus(arg);
Form2 frmChild=new Form2 ();
frmChild.Owner = this;
frmChild.ShowDialog();

这里的顺序搞错了,下面这样应该可以的:

Form2 frmChild=new Form2 ();
frmChild.Owner = this;
frmChild.ShowDialog();
OnfrmLostFocus(arg);

------解决方案--------------------
OnfrmLostFocus(arg);
Form2 frmChild=new Form2 ();
frmChild.Owner = this;
frmChild.ShowDialog();

这里的顺序搞错了,下面这样应该可以的:

Form2 frmChild=new Form2 ();
frmChild.Owner = this;
frmChild.ShowDialog();
OnfrmLostFocus(arg);

--------------------------------------
这里也错了吧`~

应该在打开窗体前就已经把参数传递过去了`
Form2 frmChild=new Form2 ();
frmChild.Owner = this;
OnfrmLostFocus(arg);
frmChild.ShowDialog();
------------------------------------

还有 为何不用直接form2的构造函数接收参数???
Form2 frmChild=new Form2 ();
frmChild.Owner = this;
frmChild.ShowDialog(arg);


form2的构造函数


public Flag(DataTable dt)
{
_dt = dt;
InitializeComponent();
}
------解决方案--------------------
Form2 frmChild=new Form2 ();
frmChild.Owner = this;
OnfrmLostFocus(arg);
frmChild.ShowDialog();