C#實現視窗之間的傳值

來源:互聯網
上載者:User

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

}

}

}

  以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.