Ahmed Fantar Ahmed Fantar - 3 months ago 18
C# Question

Add an item to a combobox with code from a second form

My problem is very simple: i have a combobox in form1, i have a button that open form2 to write into a textbox the new item to add. Here my code:
Form1:

public static string new_item;
private void btn1_Click(object sender, EventArgs e)
{

Form2 f2= new Form2();
f2.ShowDialog();
}


Form2:

private void btn1_Click(object sender, EventArgs e)
{
Form1.new_item = textBox1.Text;
combobox.Items.Add(new_item);
this.Close();
}


But the new item is not added to my comobobox.
I tried to refresh th combobox but i have the same result.
Thank you.

Answer

You need to add the item to your ComboBox after closing Form2:

public static string new_item;
private void btn1_Click(object sender, EventArgs e)
{
    Form2 f2= new Form2();
    f2.ShowDialog();
    comboBox1.Items.Add(new_item);  //this is missing in your code
}

But a better way would be creating a public property in Form2 to pass the string back:

public string Value { get; set; }

private void btn1_Click(object sender, EventArgs e)
{
    this.Value = textBox1.Text; //pass the TextBox value to the property
    this.DialogResult = DialogResult.OK; // Cancel would mean you closed/canceled the 
                                         // form without pressing OK-Button (btn1)
    this.Close();
}

Than in Form1 you can access the property and add the new item:

private void btn1_Click(object sender, EventArgs e)
{
    Form2 f2= new Form2();
    if(f2.ShowDialog() == DialogResult.OK) //check the result
    {
        comboBox1.Items.Add(f2.Value);//Add the new item
    }
}