Question

Form

In all of these tabs, I have a combobox with different functions as strings. I want the text under Preview (it's a richtextbox with "Nothing is selected." as a default string) to change whenever I select an item in each of the different tabs' comboboxes. Any idea how I can do that?

Was it helpful?

Solution

You could set every TextChanged event of all of your combobox to the same event handler

 comboBox1.TextChanged += CommonComboTextChanged;
 comboBox2.TextChanged += CommonComboTextChanged;
 comboBox3.TextChanged += CommonComboTextChanged;
 comboBox4.TextChanged += CommonComboTextChanged;


private void CommonComboTextChanged(object sender, EventArgs e)
{
    ComboBox cbo = sender as ComboBox;
    richTextBox.Text = cbo.Text;
}

However, if you change the DropDownStyle of your combos to ComboBoxStyle.DropDownList then you could use the SelectedIndexChanged event that will be triggered only when your user changes the item selected by using the DropDown List.

 comboBox1.SelectedIndexChanged += CommonComboIndexChanged;
 comboBox2.SelectedIndexChanged += CommonComboIndexChanged;;
 comboBox3.SelectedIndexChanged += CommonComboIndexChanged;;
 comboBox4.SelectedIndexChanged += CommonComboIndexChanged;;


 private void CommonComboIndexChanged;(object sender, EventArgs e)
 {
    ComboBox cbo = sender as ComboBox;
    richTextBox.Text = cbo.Text;
 }

Finally to set the content of the RTB to the one of the combo in the current tab page you need to handle the TabChanged event of your tabControl

 private void tabControl1_Selected(object sender, TabControlEventArgs e) 
 {
     switch(e.TabPageIndex)
     {
         case 0:
            richTextBox.Text = comboBox1.Text;            
            break;
         // so on for the other page and combos
     }
 }

Or if your comboboxes share a common initial part of their names

 private void tabControl1_Selected(object sender, TabControlEventArgs e) 
 {
    var result = e.TabPage.Controls.OfType<ComboBox>()
                .Where(x => x.Name.StartsWith("cboFunction"));
    if(result != null)
    {
        ComboBox b = result.ToList().First();
        richTextBox.Text = comboBox1.Text;            
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top