D4M3
D4M3

Reputation: 5

Getting selected values from combobox

I have 15 combobox controls that are populate with data from a db.. (being lazy) I've created a list of combo boxes that checks the SelectedIndex of those 15 comboboxes:

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

Ideally, what I'm trying to accomplish is to check the object cboSv1..15 get the selected values.

Upvotes: 0

Views: 595

Answers (2)

Arslan Ali
Arslan Ali

Reputation: 460

use the code for getting text and value from selected combo controls.

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

Use value or text to compare.

Upvotes: 0

Flydog57
Flydog57

Reputation: 7111

I'm not sure why you are doing what you are doing, but (assuming I am understanding you), if I were going to do it, my solution would look something like (for three combo boxes):

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

Upvotes: 0

Related Questions