C#實現視窗之間的傳值
本文給大家介紹的是C#中利用靜態類和靜態變數來實現視窗間傳值的方法和樣本,非常的實用,有需要的小夥伴可以參考下。
為瞭解決在多個視窗之間的傳值問題,我們可以通過設定靜態類和靜態變數的辦法來實現視窗間值的傳遞
表單一代碼
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
//表單1的代碼 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { sharedclass.sharedvalue = textBox1.Text.ToString(); //靜態變數的用法:類名.變數名 賦值給靜態變數 Form2 frm2 = new Form2(); frm2.Show(); } } public static class sharedclass //在命名空間設定一個靜態類sharedclass,不要放置在form1前面 { public static string sharedvalue; //設定一個靜態變數sharedvalue } } |
表單2代碼
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
//表單2的代碼 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form2 : Form { public Form2() { InitializeComponent(); textBox1.Text = sharedclass.sharedvalue; //靜態變數傳入給視窗2的textBox } } } |
以上所述就是本文的全部內容了,希望大家能夠喜歡。