Jaddy Boy
Jaddy Boy

Reputation: 9

C# - Display instantly a string in textbox coming from a different form

I'm in the 1st form, so I want to pass the ID to the 2nd Form and display it there in a textbox. So I did this.

In form 1:Assume inside using{}

public partial class First_Form: Form
{
   public void test(){
        Main_Menu_Form f2 = new Main_Menu_Form();
       f2.selectedid = id;
        f2.Show();
   }
}

In form 2: Assume inside using{}

public partial class Main_Menu_Form: Form
{
    public int selectedid;
    public Main_Menu_Form()
    {
        InitializeComponent();

        textbox1.Text = selectedid;
    }
  }

What I want is when I opened the new Form (Form2) I want to display the selected id immediately in the form2 textbox as the Form2 loads. I don't know whats wrong with this, this should display because when I tried to place textbox1.Text = selectedid; , it will work. But on form initialization or load, It won't.

Form 2: I tried also this but won't work

    private void Main_Menu_Form_Load(object sender, EventArgs e)
    {
       textbox1.Text = selectedid;
    }

Upvotes: 0

Views: 387

Answers (1)

Rufus L
Rufus L

Reputation: 37070

One way to do this is to create a public property in Form2 for the selected id, and in the Form_Load event, set the Text property of the textbox to that value:

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public int SelectedId { get; set; }

    private void Form2_Load(object sender, EventArgs e)
    {
        textBox1.Text = SelectedId.ToString();
    }
}

Then in Form1, you set the value of that property and show the form (I'm using a button Click event):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var f2 = new Form2();
        f2.SelectedId = 100;
        f2.Show();
    }
}

Upvotes: 2

Related Questions