為了解決在多個窗口之間的傳值問題,我們可以通過設置靜態類和靜態變量的辦法來實現窗口間值的傳遞
窗體一代碼
//窗體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代碼
//窗體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 } }}
以上所述就是本文的全部內容了,希望大家能夠喜歡。
新聞熱點
疑難解答