• 窗体间动态传值


    此文转载自:https://blog.csdn.net/promsing/article/details/109680661

     
    目录

    一、声明公有静态变量

    在一个类中声明公有静态变量,其他任何地方都可以使用。(99+处引用)

    二、更改Form.designer.cs文件,将控件的访问权限改为public,供其他窗体访问

    designer.cs文件的最后,更改为公有

    public  System.Windows.Forms.TextBox textBox1;

     其他窗体中直接调用

    Form2 form2 = new Form2();  //new一个窗体的实例
    form2.textBox1.Text = "5678";   //直接就能‘点’出来

    三、利用委托

    委托是一个引用类型,保存方法的指针,它指向一个方法。一旦为委托分配了方法,委托将于该方法具有完全相同的行为,当我们调用委托的时候这个方法立即被执行。

    子窗体点击“加入购物车”,父窗体的购物清单中立即显示,刚刚所选的内容。

    子窗体中定义委托和事件。

    public delegate void TransfDelegate(ListViewItem transf);  //声明委托
    public partial class FrmCustomerShop : Form
    {
         public FrmCustomerShop()
         {
             InitializeComponent();
         }
    
        public static string productName;
        public event TransfDelegate TransfEvent1;  //声明事件
        private void btnOK_Click(object sender, EventArgs e)  //加入购物车
        {
             //将购买信息传入购物清单
             int sumCash= int.Parse(txtBuyCount.Text) * int.Parse(lbPrice.Text);//总金额=单价*数量
             ListViewItem item = new ListViewItem();
             item.Text = lbProductName .Text;//商品的名称
             item.SubItems.Add(lbPrice.Text);  //单价
             item.SubItems.Add(txtBuyCount.Text);//购买的数量
             item.SubItems.Add(sumCash.ToString());  //总金额
             TransfEvent1(item);  //传入另一个控件中
    
         }
     }

    父窗体中注册事件,及事件处理的方法。

    private void CustomerShop_Load(object sender, EventArgs e)
    {    //可以写在窗体加载事件中,也可以写在其他控件的单击事件中
         FrmCustomerShop frmShop = Singleton<FrmCustomerShop>.CreateInstrance(); //单例模式
         frmShop.TransfEvent1 += frm_TransfEvent;  //注册事件
        
    }
    void frm_TransfEvent(ListViewItem item)  //事件处理方法
    {
          if (!lvBillLists.Items.Contains(item))//如果List中不存在,加入其中!
          {
               lvBillLists.Items.Add(item);
          }               
    }

    窗体间动态传值的三种方法到这里就结束了,第一种比较简单也最常用,比较适合静态变量。第二种适用范围比较有限,技术性一般。   第三种适用范围比较广,能够联动,技术性比较强,同时也是三者中最难的。

    如果本篇博客对您有一定的帮助,大家记得留言+点赞哦。

       

    更多内容详见微信公众号:Python测试和开发

    Python测试和开发

  • 相关阅读:
    年薪百万必备能力
    二叉搜索树
    字符串和字符串模式匹配
    2006最后寄语
    “豆瓣”式推荐
    什么是LOMO?
    大国崛起
    马季之死
    时间的价值(The Value Of Time)
    我读雅虎的“花生酱宣言”
  • 原文地址:https://www.cnblogs.com/phyger/p/14058607.html
Copyright © 2020-2023  润新知