0

i have a problem with C# code for combo box my code is here

cmbProjectName.Items.Clear();
if (obds.Tables.Count > 0 && obds.Tables[0].Rows.Count > 0)
{
    for (int iCount = 0; iCount < obds.Tables[0].Rows.Count; iCount++)
    {
        cmbProjectName.Items.Add(obds.Tables[0].Rows[iCount]["Project_Name"].ToString()); 
    }
}

Value Add in Combo Box but i will to add the index of this item my self for further operation on other search please suggest me...

Christos
  • 53,228
  • 8
  • 76
  • 108
user3887728
  • 31
  • 2
  • 8

3 Answers3

0

You can create a class

private class Project
{
     public int ID {get; set;}
     public string Name {get; set;}

     public Project (int _id, string _name)
     {
          ID = _id;
          Name = _name
     }
}

Then, you transform the method in this way

List<Project> listPrj = new List<Project>();

 if (obds.Tables.Count > 0 && obds.Tables[0].Rows.Count > 0)
 {
        for (int iCount = 0; iCount < obds.Tables[0].Rows.Count; iCount++)
        {
            listPrj.Add(new Project(int.Parse(obds.Tables[0].Rows[iCount]["Project_ID"].ToString()), obds.Tables[0].Rows[iCount]["Project_Name"].ToString());
        }    
 }

cmbProjectName.DisplayMember = Name;
cmbProjectName.ValueMember = ID;
cmbProjectName.DataSource = listPrj;
JAEP
  • 363
  • 2
  • 5
  • 12
0

JAEP's solution can also be applied in desktop apps. Please check this MSDN page about ValueMember.

After you specify DisplayMember, ValueMember, and DataSource, you can get selected text and selected value with ComboBo.SelectedText and ComboBo.SelectedValue.

Or you simply just want the index, you can use ComboBo.SelectedIndex.

Khoait
  • 328
  • 4
  • 18
0

JAEP's solution using class will work. Binding to a dictionary is another way, here you don't have to create extra class. Source SO question

The code will be like below in your case. Replace iCount with the index you want.

cmbProjectName.Items.Clear();
Dictionary<int, string> projectsDictionary = new Dictionary<int, string>();
if (obds.Tables.Count > 0 && obds.Tables[0].Rows.Count > 0)
{
    for (int iCount = 0; iCount < obds.Tables[0].Rows.Count; iCount++)
    {
        projectsDictionary.Add(iCount, obds.Tables[0].Rows[iCount]["Project_Name"].ToString());
    }
}   
cmbProjectName.DataSource = new BindingSource(projectsDictionary, null);
cmbProjectName.DisplayMember = "Value";
cmbProjectName.ValueMember = "Key";

Code to retrieve key or value.

string value = ((KeyValuePair<int, string>)cmbProjectName.SelectedItem).Value;
int key =  ((KeyValuePair<int, string>)cmbProjectName.SelectedItem).Key;
Community
  • 1
  • 1
Baga
  • 1,354
  • 13
  • 24
  • Thanks but key value is same as selected index change value – user3887728 Aug 01 '14 at 19:05
  • Yes, I have used iCount as the key. You have to replace iCount with your index value in this statement `projectsDictionary.Add(iCount..` – Baga Aug 01 '14 at 20:56