Today I had some troubles finding out how to implement a simple ComboBox in my C# Windows Forms program. Here's my solution because maybe somebody else can use it.
1) Add a ComboBox to the project (drag and drop from the Toolbox)
2) Add two labels to the project (label1.Visible = false, label2.Visible = true)
Add the code to Form1.cs:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("Europe");
comboBox1.Items.Add("America");
comboBox1.Items.Add("Russia");
}
public void combo_selected(object Sender, EventArgs e)
{
label1.Text = comboBox1.Text;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.SelectedIndexChanged += new EventHandler(this.combo_selected);
comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;
comboBox1.SelectedItem.ToString();
label1.Text = comboBox1.Text;
}
// Now check if everything has worked !
private void button1_Click(object sender, EventArgs e)
{
label2.Text = label1.Text;
}
}
}
Now, debug, make a selection in the combox and press the button. If everything went well, label2 will show the item you have chosen in the combobox.
Recent Comments