如何在两种表单之间传递值

时间:2015-05-30 18:01:32

标签: c# forms

所以我有两种形式,我想将打开的表单(Form2)中的字符串值传递给主窗体(Form1)

案例是:

使用Form1中的按钮显示Form2,然后Form2在列表框中显示进程列表。我想将Form2中的进程名称(字符串,带有slctItm变量)传递到Form1中的textBox,并在Form2中使用一个按钮。请帮帮我。

代码(form2):

...
public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        Process[] prc = Process.GetProcesses();
        foreach ( Process aPrc in prc)
        {
            listBox1.Items.Add(aPrc.ProcessName);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string slctItm;
        slctItm= listBox1.GetItemText(listBox1.SelectedItem);
        //how to pass this value?
    } 
...

感谢

4 个答案:

答案 0 :(得分:0)

在这里。使用此代码从表单1到表单2获取值。

private int value_u_want;

public int Value_u_want
{
    get{return Value_u_want;}
    set{value = value;}

答案 1 :(得分:0)

您可以在Form2的构造函数中传递对Form1的引用。当您单击Form2上的按钮以获取列表框值时,您调用Form1中的方法,如form1.UpdateTextBox(String listboxValue)

答案 2 :(得分:0)

我建议使用Reactive Extensions(RX)。创建一个Subject,然后在两个表单之间共享此类。然后,您可以在一个表单中创建事件,并以另一种形式订阅事件。

这意味着Form1几乎完全与Form2分离,但它们仍然可以通信。

在完全不相关的说明中,我还建议使用WPF而不是WinForms。

答案 3 :(得分:-1)

这很简单。只需使用私有变量来声明,然后公开使用该值以任何形式或用户控制进行访问。