简体   繁体   中英

Get text from combobox in selected tab

形成

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?

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;            
    }
}

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