1
votes

I am trying to Insert/Add first value as "Select One" to my combobox in C# Windows Forms Application. Combo box style is "DropDownList".

I am fetching cities data from database and binding combobox.

I know that I already set 1 datasource to combobox and again trying to add . I want to add "Select One" dynamically ,How to do this?

Here is the Filling cities code.

    public void Fill_CitiesDDL()
    {
        try
        {
            cmbCity.Items.Clear();
            DataSet ds = new DataSet();
            ds = Select_Cities();
            ds.DataSetName = "Tbl_City";
            if (ds.Tables.Count > 0)
            {
                if (ds.DataSetName == "Tbl_City" && ds.Tables[0].Rows.Count > 0)
                {
                    Dictionary<string, string> test = new Dictionary<string, string>();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        test.Add(ds.Tables[0].Rows[i]["City_Name"].ToString(), ds.Tables[0].Rows[i]["City_Id"].ToString());
                    }
                    this.cmbCity.DataSource = new BindingSource(test, null);
                    this.cmbCity.DisplayMember = "Key";
                    this.cmbCity.ValueMember = "Value";
                    this.cmbCity.Items.Add("Select One ");--->Error is Coming at this Point
                }
                else
                {
                    lblEmployerError.Text = "No data for City";
                }
            }
            else
            {
                lblEmployerError.Text = "City Table does not exists";
            }
        }
        catch (NullReferenceException nr)
        {

            lblEmployerError.Text="Null value exception caused, try again later..!!";
        }
        catch (SqlException sql1)
        {

            lblEmployerError.Text="Connection to server failed or network problem..!!";
        }
        catch (Exception ex)
        {

            lblEmployerError.Text="Fatal error catched, contact system administrator...!!";
        }
    }

Pls. give me solutions to this problem.

1

1 Answers

4
votes

You will need to add your "Select One" value to the test dictionary prior to binding to the test as your data source.

test.Add("Select One ","Select One ");

then

this.cmbCity.DataSource = new BindingSource(test, null);