简体   繁体   中英

Add Items in ComboBox using Textbox Value from another form in C#

I have 2 Window Forms, Form1 and Form2 . Form1 has a ComboBox and Form2 has a Textbox and a Button .

I hope you can help me with this one. What I would like to happen is, if I input a string value in the TextBox in Form2 and hit the Button1 that is also located in my Form2 , the value of that TextBox will be an item for my ComboBox that is located in my Form1 .

I just would like to ask if is there any way that we can do this? Could you provide an example for me? I'm looking forward to your help.

It would help a lot if you'd include what attempt code you have so far, and/or what obstacles you're encountering, but nonetheless this is a simple problem that's a bit difficult to search for, so hopefully this will help.

First, I'm assuming you've instantiated and displayed both forms. Next you'll want to find the Designer.cs (formNameHere.Designer.cs) file in your Solution Explorer, then locate the variable declaration for your combo box (should be near the bottom). Change its access modifier from 'private' to something more appropriate.

Now go back to your Form1 code file and add this to your button click event handler:

form2.comboBox1.Items.Add(textBox1.Text);

... where 'form2', 'comboBox1', and 'textBox1' are your child form, combo box, and text box from which you are sending the new combo box item.

Let me know if you have any further questions.

I think best option is to communicate between the forms through events . So on button click event trigger an event and subscribe to it from the Form1. When the event is raised, add the text to the combobox

In Form2:

internal event EventHandler<string> NewItemToAdd;
void button1_clicked(object sender, EventArgs e)
{
    if(NewItemToAdd != null)
        NewItemToAdd(textbox.Text);
}

In Form1 subscribe to the event NewItemToAdd and add the text to your combobox when the event is raised

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM