从选定选项卡中的组合框中获取文本

时间:2014-02-06 12:49:39

标签: c# winforms combobox tabcontrol

Form

在所有这些选项卡中,我有一个组合框,其功能与字符串不同。我希望每次在每个不同选项卡的组合框中选择一个项目时,预览下的文本(它是一个富文本框,其中“没有选择任何东西。”作为默认字符串)。知道我该怎么做吗?

1 个答案:

答案 0 :(得分:0)

您可以将所有组合框的每个TextChanged事件设置为相同的事件处理程序

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

但是,如果将组合的DropDownStyle更改为ComboBoxStyle.DropDownList,则可以使用SelectedIndexChanged事件,该事件仅在用户更改使用DropDown列表选择的项目时才会触发。

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

最后,要将RTB的内容设置为当前标签页中的一个组合,您需要处理tabControl的TabChanged事件

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

或者,如果您的组合框共享其名称的共同初始部分

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