0

So I have two forms, and i want to pass a string value from opened form (Form2) to the main form (Form1)


The case is:

Show Form2 with a button in Form1, then Form2 shows a process list in a listbox. I want to pass the process name (string, with slctItm variable) from Form2 into a textBox in Form1 with a button in Form2. Please help me.

Code (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?
    } 
...

thanks

Evan Gunawan
  • 387
  • 4
  • 17

4 Answers4

0

here it is. Use this code to get value from form 1 to form 2.

private int value_u_want;

public int Value_u_want
{
    get{return Value_u_want;}
    set{value = value;}
nasr18
  • 75
  • 1
  • 3
  • 13
0

you could pass a reference to Form1 in Form2's contructor. When you click the button on Form2 to get the listbox value, you call a method in Form1 such as form1.UpdateTextBox(String listboxValue)

Arrakis
  • 43
  • 2
  • 7
0

I'd suggest using Reactive Extensions (RX). Create a Subject then share this class between the two forms. You can then create events in one form and subscribe to the events in another form.

This means that Form1 is almost completely decoupled from Form2, but they can still communicate.

On a completely unrelated note, I'd also suggest using WPF rather than WinForms.

Contango
  • 76,540
  • 58
  • 260
  • 305
-1

it's very simple. Just use private variable to declare and then use that value publicly to access in any form or user control.

nasr18
  • 75
  • 1
  • 3
  • 13