Dynamic value transfer between forms

 
table of Contents

1. Declare public static variables

Declaring public static variables in a class can be used anywhere else. (99+ references)

2. Change the Form.designer.cs file and change the access permission of the control to public for other forms to access

At the end of the designer.cs file , change it to public !

public  System.Windows.Forms.TextBox textBox1;

 Call directly in other forms

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

3. Use entrustment

A delegate is a reference type that holds a pointer to a method, which points to a method. Once the method is assigned to the delegate, the delegate will have exactly the same behavior as the method, and the method will be executed immediately when we call the delegate.

Click "Add to Shopping Cart" on the child form, and the shopping list of the parent form will immediately show the selected content.

The delegates and events are defined in the subform.

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);  //传入另一个控件中

     }
 }

Register events in the parent form and the method of event handling.

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

This is the end of the three methods of dynamically passing values ​​between forms. The first one is simpler and most commonly used, and is more suitable for static variables. The second type has a limited scope of application and general technicality. The third type has a wide range of applications, can be linked, and is more technical. It is also the most difficult of the three.

If this blog is helpful to you, please remember to leave a message + like it.

Guess you like

Origin blog.csdn.net/promsing/article/details/109680661