1

I seem to have a problem passing some strings on from one form to another. I have two listBoxes on Form1 but i want to use Form2 to pass the information on into the listBoxes in Form1. In Form2 i have a button_Click function that calls a function in Form1 with params string a and string b.

private void button_Click(object sender, EventArgs e){
Form1 frm = new Form1();
frm.AddItemToListBox(txtBox1.Text,txtBox2.Text);
}

Below is the code to call the function AddItemToListBox in Form1.
Above is the function AddItemToListBox in Form1.

AddItemToListBox(string a, string b){
listBox1.Items.Add(a);
listBox2.Items.Add(b);
}

However this does not add the strings into the listboxes. There are no error messages or anything. I have also tried declaring 2 public strings STR1 and STR2

AddItemToListBox(string a, string b){
listBox1.Items.Add(a);
listBox2.Items.Add(b);
STR1 = a;
STR2 = b;
}

But if i used a button that displays STR1 and STR2's value. They will be "", String.Empty. Nothing shows up in the MessageBox that displays the value. However, if i place the MessageBox.Show(a); and MessageBox.Show(b); in the AddItemToListBox function, the strings will be correctly shown but still not added to the listbox.

This has been frustrating me for like 2 hours now and i want to find out why and how to actually use that method to add an item to a listbox if its possible. Greatest thanks in advance.

3 Answers 3

3

Try to add a frm.Show() at the end of this method.

private void button_Click(object sender, EventArgs e)
{ 
    Form1 frm = new Form1(); 
    frm.AddItemToListBox(txtBox1.Text,txtBox2.Text); 
    frm.Show();
} 

But I'm sure that this doesn't solve your problem. Just show you that you need to reference the correct Form1. I think you are creating a new instance of Form1, yuo need to address the correct one

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the prompt reply. That worked. I understand it now.
1
Form1 frm = new Form1();

The above will initialize a new form, it will not change an existing instance of Form1.

1 Comment

Thanks. I understand it now. Is there a way to not initialize a new form? Like just calling from Form1
0

Either your inputs are empty, so debugwatch txtBox1.Text before calling

frm.AddItemToListBox(txtBox1.Text,txtBox2.Text);

Or the form does not redraw after adding your string. This can be forced by using

listBox1.Invalidate();
listBox2.Invalidate();

right after adding the strings

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.