窗體間動態傳值

 
目錄

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

窗體間動態傳值的三種方法到這裏就結束了,第一種比較簡單也最經常使用,比較適合靜態變量。第二種適用範圍比較有限,技術性通常。   第三種適用範圍比較廣,可以聯動,技術性比較強,同時也是三者中最難的。

若是本篇博客對您有必定的幫助,你們記得留言+點贊哦。

相關文章
相關標籤/搜索