窗体间动态传值

 
目录

1、声明公有静态变量

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

2、更改Form.designer.cs文件,将控件的访问权限改成public,供其余窗体访问

designer.cs文件的最后,更改成公有博客

public  System.Windows.Forms.TextBox textBox1;

 其余窗体中直接调用string

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

3、利用委托

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

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

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

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);
      }               
}

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

若是本篇博客对您有必定的帮助,你们记得留言+点赞哦。

相关文章
相关标签/搜索