从组合框获取所选值

时间:2018-07-19 03:41:04

标签: c# winforms combobox

我有15个组合框控件,其中填充了来自数据库的数据。(很懒),我创建了一个组合框列表,用于检查这15个组合框的SelectedIndex:

 List<ComboBox> controls = new List<ComboBox>();                
 if (cboSrv1.SelectedIndex > -1 ..||.. cboSrv15.SelectedIndex > -1)
 {
    string msg = string.Format("Process {0} with selected servers?.\n\nProceed?", txtTypeAppName.Text.ToString());
    string title = "SELECTED SERVER";
    DialogResult dr = MessageBox.Show(msg, title, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
    if(dr == DialogResult.Yes)
    {
       object[] cboSvr = { cboSrv1, ..,.. cboSrv15 };
       foreach (ComboBox i in cboSvr)
       {                            
         if (i.SelectedIndex > -1)
         {
           controls.Add(i);                                
         }                            
       }
     }                    
  }

理想情况下,我要完成的工作是检查对象cboSv1..15是否获得选定的值。

2 个答案:

答案 0 :(得分:0)

我不确定您为什么要做自己的工作,但是(假设我了解您),如果我要这样做,我的解决方案将类似于(对于三个组合框):

    var comboBoxes = new List<ComboBox> { comboBox1, comboBox2, comboBox3 };
    var results = new Dictionary<string, string>();
    foreach (var comboBox in comboBoxes)
    {
        if (comboBox.SelectedIndex != -1)
        {
            results.Add(comboBox.Name, comboBox.SelectedItem.ToString());
        }
    }

答案 1 :(得分:0)

使用代码从选定的组合控件中获取文本和值。

List<ComboBox> list = new List<ComboBox>();
        foreach(var combo in list)
        {
            if(combo.SelectedIndex>-1)
            {
                //check code here
                string value=combo.SelectedValue.ToString();
                string text=combo.SelectedText;
            }
        }

使用值或文本进行比较。

相关问题