当前位置:   article > 正文

c#利用事件完成页面之间的交互_c#事件跨页面调用

c#事件跨页面调用

1.创建窗体FrmEvent和FrmEventExpend,将FrmEventExpend添加的信息显示到FrmEvent窗体中
在这里插入图片描述
在这里插入图片描述
2.创建 ExpendNew类存储信息

public  class ExpendNew
    {
        public string ItemName { get; set; }
        public string Remark { get; set; }
        public decimal Amount { get; set; }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3.声明事件,ExpendArgs用来表示需要传递的消息,必须继承EventArgs

 public event EventHandler<ExpendArgs> ShowExpendInfoEvent;
  public class ExpendArgs:EventArgs
    {
        public ExpendNew ExpendInfo { get; set; }
        public ExpendArgs(ExpendNew info)
        {
            ExpendInfo = info;
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  1. FrmEvent来绑定事件,表名事件需要完成的任务(注意:事件绑定函数只能使用+=或者-=,不能像委托一样直接使用=)
private void btnExpend_Click(object sender, EventArgs e)
        {
            FrmEventExpend frm = new FrmEventExpend();
            // frm.ShowExpendInfoEvent += Frm_ShowExpendInfoEvent;//事件的订阅
            frm.ShowExpendInfoEvent += Frm_ShowExpendInfoEvent1;
            frm.Show();
        }
private void Frm_ShowExpendInfoEvent1(object sender, ExpendArgs e)
        {
            ExpendNew info = e.ExpendInfo;
            lblExpendList.Text += info.ItemName + "," + info.Remark + "," + info.Amount + "\r\n";
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

5.当点击FrmEventExpend的支出记账的时候,需要事件响应

         private void btnInRecord_Click(object sender, EventArgs e)
        {
            //信息接收
            string itemName = txtItemName.Text;
            string remark = txtRemark.Text;
            decimal amount = decimal.Parse(txtAmount.Text);
            //封装
            ExpendNew expend = new ExpendNew()
            {
                ItemName = itemName,
                Remark = remark,
                Amount = amount
            };
            list.Add(expend);
            int length = list.Count;
            if(length-count==1)
            {
                //触发事件,调用事件
                //ShowExpendInfoEvent?.Invoke(expend);  //?  如果事件不为空则调用,否则不调用 
                ShowExpendInfoEvent?.Invoke(this, new ExpendArgs(expend));  
                count = length;
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号