Vereonix
Vereonix

Reputation: 1413

Set combo box visible text to nothing after populating it via a binding source

I populate my combo boxes with a binding source using a dictionary, however this results in the top of the list being visible as default.

I'd like to have the combo box display nothing after it has been populated, as events trigger when the user selects a dropdown option(SelectedIndexChanged). So with an option which may be the one they need they have to select it even though it appears to already be selected.

Dictionary creation:

        public Dictionary<int, string> Get_List_of_SchemesID()
        {
            Dictionary<int, string> comboSource = new Dictionary<int, string>();

            using (SqlConnection cnn = new SqlConnection(connectionString))
            {
                cnn.Open();
                string query = "SELECT [idGMRScheme],[SchemeName] FROM [DBA_Admin].[dbo].[GMR_Schemes]";

                using (SqlCommand command = new SqlCommand(query, cnn))
                using (SqlDataReader reader = command.ExecuteReader())
                    while (reader.Read())
                    {
                        comboSource.Add((int)reader["idGMRScheme"], (string)reader["SchemeName"]);
                    }
            }
            return comboSource;
        }

Combo population:

    public void Populate_SchemesID_Combolists(Dictionary<int, string> comboSource)
    {
        cb_Schemes.DataSource = new BindingSource(comboSource, null);
        cb_Schemes.ValueMember = "Key";
        cb_Schemes.DisplayMember = "Value";
    }

Upvotes: -1

Views: 195

Answers (2)

LP. Gon&#231;alves
LP. Gon&#231;alves

Reputation: 480

I can see two different approaches.

First

Change this method to add a new item to your comboBox:

public void Populate_SchemesID_Combolists(Dictionary<int, string> comboSource)
{
    comboSource.Add(0, ""); //To be the first item displayed
    // or
    comboSource.Add(0, "Select the Scheme"); // To be default
    // maybe you'll need to order by the key asc.

    cb_Schemes.DataSource = new BindingSource(comboSource, null);
    cb_Schemes.ValueMember = "Key";
    cb_Schemes.DisplayMember = "Value";
}

Second

public void Populate_SchemesID_Combolists(Dictionary<int, string> comboSource)
{
    cb_Schemes.DataSource = new BindingSource(comboSource, null);
    cb_Schemes.ValueMember = "Key";
    cb_Schemes.DisplayMember = "Value";

    cb_Schemes.Text = ""; 
    //or 
    cb_Schemes.Text = "Select the Scheme"; 
}

Note: For the two methods you'll need to check if it's selected the correct item before doing anything with the comboBox selected item like:

if (cb_Schemes.SelectedItem.ToString() != "Select the Scheme" || cb_Schemes.SelectedItem.ToString() != "")
{
    //do anything
}

I hope you get the idea.

Upvotes: 0

DimitarD
DimitarD

Reputation: 117

You could try setting the combo's SelectedIndex to -1:

cb_Schemes.SelectedIndex = -1;

Upvotes: 1

Related Questions