【问题标题】:Getting selected values from combobox从组合框中获取选定的值
【发布时间】:2018-07-19 03:41:03
【问题描述】:

我有 15 个组合框控件,其中填充了来自 db 的数据。(懒惰)我创建了一个组合框列表,用于检查这 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 获取选定的值。

【问题讨论】:

  • 您的问题是什么?如果您想了解更多关于 C# 中 Array 的信息,可以阅读 C# programming Guide

标签: c# winforms combobox


【解决方案1】:

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

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

【讨论】:

  • 我接受这一点,因为我能够从组合框中访问我需要的值。 - 谢谢
【解决方案2】:

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

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

使用值或文本进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    • 2013-08-15
    • 2011-10-17
    相关资源
    最近更新 更多