首页 > 代码库 > 事件与委托更新父窗体数据,简单比较

事件与委托更新父窗体数据,简单比较

1.委托更新父窗页面。

     例如,功能:父窗体A,子窗体B,由A打开B窗体,更新A窗体数据

      A窗体代码:

        public delegate void reflshPassenger();//声明委托

      
        private void btnAddPassenger_Click(object sender, EventArgs e)//打开B窗体按钮,并把委托窗体给B窗体
        {
            reflshPassenger reflshData = http://www.mamicode.com/getPassengers;
            new FZ_Passengers("add", reflshData).ShowDialog();
        }

          private void getPassengers()

        {

              //...dosomething

         }

     B窗体代码:

      A.reflshPassenger reflshpassenger; //声明A窗体委托

      public FZ_Passengers(string _strState, formSubmitOrder.reflshPassenger _reflsh)
        {
            InitializeComponent();
            strState = _strState;
            reflshpassenger = _reflsh;//接受主窗体传递过来的委托
        }

       //最后在需要调用的位置,调用即可:

       if(reflshpassenger!=null)

       {

        reflshpassenger()

       }

 

 

 

2.基于事件:

  窗体A代码:

  B b;

  注册事件:

        B= new Frm_B();
          
            B.eventLookUp += new EventHandler(frm_ValueChanged);//注册事件,要在ShowDialog之前实现
            B.ShowDialog();

  实现事件:

             if (B.strName != "")
            {
                this.lb_Sub.Text = frm.strName.Trim();
            }
            else
            {
                return;
            }

B窗体代码:

 事件声明:

                   public event EventHandler eventLookUp;
                   public string strName { get; set; }//声明字符串

                   //在具体的位置实现事件

                     if (eventLookUp != null)
                {
                    strName = dgv_DataSource.Rows[e.RowIndex].Cells["userName"].Value.ToString().Trim();
                    this.eventLookUp(sender, e);
                    this.Close();
                }

 

        总结,基于事件的实现方法,更简单,效率也高点,后期的维护性也高些!~