Click here to Skip to main content
16,022,255 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I cannot add --Select-- as the first item in a combobox loaded from a SQL table.

What I have tried:

    string query = "SELECT Name,ID from Contacts " +  
                   "ORDER BY Name" ;
    SqlDataAdapter da = new SqlDataAdapter(query, conn);
    conn.Open();
    DataSet ds = new DataSet();
     
    da.Fill(ds, "contacts");
    cbxContact.Items.Add(new { Text = "--Select--", Value = -1 });
    cbxContact.DisplayMember = "Name";
    cbxContact.ValueMember = "ID";
  
    cbxContact.DataSource = ds.Tables["contacts"];
    
}
catch (Exception ex)
{
    // write exception info to log or anything else
    MessageBox.Show("Error occured in Contacts!");
}
Posted
Comments
[no name] 24-Jul-24 16:14pm    
You are adding the "--Select--" at the end of the collection. You should use Insert to add it at the beginning.

1 solution

string query = "select '[Select]' as name, 0 as id union Select name, id from contacts";

SqlDataAdapter da = new SqlDataAdapter(query, conn);
    conn.Open();
    DataSet ds = new DataSet();     
    da.Fill(ds, "contacts");
    cbxContact.DisplayMember = "Name";
    cbxContact.ValueMember = "ID";
  
    cbxContact.DataSource = ds.Tables["contacts"].DefaultView;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900