2017-07-26 54 views
0

概述自动设置组合框的值时文本框包含文本

我有3个文本框,txt_Mobiletxt_Landlinetxt_Other。如果这3个文本框中的一个包含值,则需要根据填充的文本框自动将我的组合框(cmb_PrefconNumber)设置为字符串“Mobile”,“landline”或“other”。然后这需要自动将combobox的值设置为相应的值。 如果填充了两个以上的文本框,我需要让用户自己选择它。不过,我仍然需要用给定的值填充它。

我不确定我是否必须绑定文本框,因为我实际上没有使用该值,只是相应的字符串。我试着结合文本框在我的构造函数,像这样:

binding = new Binding("Text", cmb_PrefConNumber, "Text"); 
cmb_PrefConNumber.DataBindings.Add(binding); 

我现在有这个每个validating event handler

if (!cmb_PrefConNumber.Items.Contains("Alternative")) 
{ 
    cmb_PrefConNumber.Items.Add("Alternative"); 
    return; 
} 

然而,这些不更新自己的组合框,因为我认为这需要两个值,即intstring并进行绑定。我不确定如何在不使用文本框值时执行此操作。

回答

0

在所有3个文本框中使用TextChanged事件,并在其中启动一个像PopulateCombo(textboxID)这样的功能。对于textboxID,你为3个不同的文本框设置1,2和3,它看起来像这样:

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    if(!String.IsNullOrEmpty(textBox1.Text)) 
    { 
     PopulateCombo(1); 
    } 
} 

private void textBox2_TextChanged(object sender, EventArgs e) 
{ 
    if(!String.IsNullOrEmpty(textBox2.Text)) 
    { 
     PopulateCombo(2); 
    } 
} 

private void textBox3_TextChanged(object sender, EventArgs e) 
{ 
    if(!String.IsNullOrEmpty(textBox3.Text)) 
    { 
     PopulateCombo(3); 
    } 
} 

private void PopulateCombo(int textBoxID) 
    { 
     //With this you will get how many textBoxes have value 
     int filledTextboxes = 0; 
     if(!String.IsNullOrEmpty(textBox1.Text)) 
     { 
      filledTextboxes++; 
     } 
     if (!String.IsNullOrEmpty(textBox2.Text)) 
     { 
      filledTextboxes++; 
     } 
     if (!String.IsNullOrEmpty(textBox3.Text)) 
     { 
      filledTextboxes++; 
     } 

     //With this you will run one code if only one textbox has value and other if more than one has value 
     if(filledTextboxes == 1) 
     { 
      switch(textBoxID) 
      { 
       case 1: 
        comboBox1.Items.Clear(); 
        comboBox1.Items.Add("TextBox1"); 
        break; 
       case 2: 
        comboBox1.Items.Clear(); 
        comboBox1.Items.Add("TextBox2"); 
        break; 
       case 3: 
        comboBox1.Items.Clear(); 
        comboBox1.Items.Add("TextBox3"); 
        break; 
      } 
     } 
     else 
     { 
      comboBox1.Items.Clear(); 
      MessageBox.Show(String.Format("All items cleared because there are {0} boxes with value", filledTextboxes)); 
     } 
    } 
+0

干杯,但我如何填充我的组合框?我已经尝试过#case 1: //填充移动组合框的组合框 cmb_PrefConNumber.Items.Add(“Mobile”); 休息; 情况2: //填充带有固定电话号码值的组合框 cmb_PrefConNumber.Items.Add(“Landline”); 休息; ' –

+0

而那不行?它说什么? –

+0

filledTextboxes var没有正确递增,textboxId填充正常,但它也可以跳到其他地方 –