1. 程式人生 > 實用技巧 >窗體間動態傳值

窗體間動態傳值

此文轉載自:https://blog.csdn.net/promsing/article/details/109680661#commentBox

目錄

一、宣告公有靜態變數

二、更改Form.designer.cs檔案,將控制元件的訪問許可權改為public,供其他窗體訪問

三、利用委託

子窗體點選“加入購物車”,父窗體的購物清單中立即顯示,剛剛所選的內容。

子窗體中定義委託和事件。

父窗體中註冊事件,及事件處理的方法。


一、宣告公有靜態變數

在一個類中宣告公有靜態變數,其他任何地方都可以使用。(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);
      }               
}

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

如果本篇部落格對您有一定的幫助,大家記得留言+點贊哦。