Skip to content

New to C# / Binding data to a combo box

doug 0

Asked Feb 14, 2005, 1:20 AM EST3 answers
Share
LinkedInX
How in the world do you bind a name,value pair to a combo box in a C# Windows Form?!? I've been trying to figure this out for the past 8 hours and CANNOT figure it out! this: cboTest.Items.Add("asd"); only adds a value... and I've Googled this thing to death.... thanks. dd

3 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Hi Add objects, but tell the combobox, which member to display. I've made a sample NameVaulePair class. public class NameValuePair { private string m_name; private object m_value; public NameValuePair(string name) : this(name, null) { } public NameValuePair(string name, object value) { this.m_name = name; this.m_value = value; } public string Name { get { return this.m_name; } } public object Value { get { return this.m_value; } set { this.m_value = value; } } Use it the following way: comboBox1.DisplayMember = "Name"; // Display NameValuePair.Name (of a given instance). comboBox1.Items.Add(new NameValuePair("FirstName", "Jony")); comboBox1.Items.Add(new NameValuePair("LastName", "Bravo")); comboBox1.Items.Add(new NameValuePair("Age", 25)); You can do that with every class/object you wannt. Hope i helped... Simon
    0
  • 0
    I am trying to bind a name/value pair into a ComboBox in C#; what's the best way to do that?
    0
  • Niradhip Chakraborty
    0

    string strSQL = "";

          string strEquipementID = "";

          string Datetime = "";

    SqlConnection sqlCon = null;

          sqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());

         SqlCommand sqlCmd = new SqlCommand();

         SqlDataAdapter adpData = null;

        SqlDataReader sdrData = null;       

     

    strSQL = "SELECT * from equipment";

            cboDatetime.Items.Clear(); // Id of dropdownlist

            cboDatetime.Items.Insert(0, "------- Select -------");

      sqlCmd.CommandText = strSQL;

            sdrData = sqlCmd.ExecuteReader();

            if (sdrData.HasRows)

             {

               if (sdrData.Read())

               {

                  strEquipementID = sdrData["id "].ToString();

                  Datetime =  sdrData["dtime "].ToString();

                  cboDatetime.Items.Add(new ListItem(Datetime, strEquipementID));

     

     

                }

             }

    sdrData.Close();

     

    Note: cboDatetime is the 'id' of combobox

    0