C# Combo Box SelectedValue Null

Ryan Ward picture Ryan Ward · Jun 25, 2013 · Viewed 12.7k times · Source

Without posting the entirety of my code (I'm just posting the offending script), I'm having a problem that seems like lots of people have had but mine seems to not respond to other recommended fixes. I'm using C# in VS2008.

Basically I have a comboBox, and when the item init is changed it goes to the code below. Essentially the code will determine which country was select (myCountryKey) and then pass that as a parameted to a stored procedure that populates a subsequent comboBox.

What's weird is, the selectedValue propert of cboCountries always shows as Null. In reading about this issue, it seemed like the dropdownStyle property was the issue, but I changed mine to DropDownList as recommended and that didn't work.

Because I use dropdowns a lot, I started playing arond and found that I can get the SelectedIndex property to work and I can use the GetItemText property to work as well (this is what the myCountryKey2 and myCountryKey3 variables are for). However what I really would like is the SelectedValue, and I've done such stuff before and just can't understand why it isn't working.

Is there any other combo box property I might have accidentally changed that might be making SelectedValue not work?

private void cboCountries_SelectedIndexChanged(object sender, EventArgs e)
        {
            SqlCommand cmd = null;
            SqlDataReader dr = null;

            try
            {
                cmd = util.SqlConn.CreateCommand();
                cmd.CommandType = CommandType.StoredProcedure;

                myCountryKey = int.Parse(this.cboCountries.SelectedValue.ToString());  //does not work, says value is null
                myCountryKey2 = int.Parse(this.cboCountries.SelectedIndex.ToString());  //Works fine
                string myCountryKey3 = this.cboCountries.GetItemText(this.cboCountries.SelectedItem).ToString(); //Works fine

                cboDivisions.Enabled = true;
                cboDivisions.Items.Clear();

                // Division parameter
                cmd.CommandText = "proc_parms_division";
                dr = cmd.ExecuteReader();
                while (dr.Read())
                    this.cboDivisions.Items.Add(new ListItem(dr["division_name"].ToString(), dr["division_key"].ToString()));

                dr.Close();
                cmd.Parameters.Clear();
            }
            catch (Exception ex)
            {
                util.LogError(ex);
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (dr != null) dr.Dispose();
                if (cmd != null) cmd.Dispose();
            }
        }

More Code:

       public frmWriteoff()
        {
            InitializeComponent();
            //this.KeyPreview = true;
            //this.KeyUp += new KeyEventHandler(frmWriteoff_KeyUp);

            // Data objects are unmanaged code.  
            // Declare them above the try{} block and always dispose of them in finally{}.
            SqlCommand cmd = null;
            SqlDataReader dr = null;

            try
            {
                this.cboCountries.DisplayMember = "Label";
                this.cboCountries.ValueMember = "Value";
                this.cboDivisions.DisplayMember = "Label";
                this.cboDivisions.ValueMember = "Value";
                this.cboBusinessUnits.DisplayMember = "Label";
                this.cboBusinessUnits.ValueMember = "Value";
                this.cboMCCs.DisplayMember = "Label";
                this.cboMCCs.ValueMember = "Value";
                this.cboNodes.DisplayMember = "Label";
                this.cboNodes.ValueMember = "Value";
                this.cboProductCodes.DisplayMember = "Label";
                this.cboProductCodes.ValueMember = "Value";


                // Country parameters
                cmd = util.SqlConn.CreateCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "proc_parms_countries_for_user";
                cmd.Parameters.Add("@whoAmI", SqlDbType.VarChar).Value = WindowsIdentity.GetCurrent().Name;
                dr = cmd.ExecuteReader();
                while (dr.Read())
                    if (dr["country key"].ToString() != "0" && dr["country key"].ToString() != "1")
                    {
                        this.cboCountries.Items.Add(new ListItem(dr["country name"].ToString(), dr["country key"].ToString()));
                    }
                cmd.Parameters.Clear();
                dr.Close();

}
            catch (Exception ex)
            {
                util.LogError(ex);
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (dr != null) dr.Dispose();
                if (cmd != null) cmd.Dispose();
            }
        }

Answer

Ryan Ward picture Ryan Ward · Jun 25, 2013

I figured it out, unbound data strikes again. When I changed my code to load my country list to a data table and then use that datatable as the source of my combobox, all was well with the world.

    public frmWriteoff()
    {
        InitializeComponent();
        //this.KeyPreview = true;
        //this.KeyUp += new KeyEventHandler(frmWriteoff_KeyUp);

        // Data objects are unmanaged code.  
        // Declare them above the try{} block and always dispose of them in finally{}.
        SqlCommand cmd = null;
        SqlDataReader dr = null;

        try
        {
            this.cboCountries.DisplayMember = "Label";
            this.cboCountries.ValueMember = "Value";
            this.cboDivisions.DisplayMember = "Label";
            this.cboDivisions.ValueMember = "Value";
            this.cboBusinessUnits.DisplayMember = "Label";
            this.cboBusinessUnits.ValueMember = "Value";
            this.cboMCCs.DisplayMember = "Label";
            this.cboMCCs.ValueMember = "Value";
            this.cboNodes.DisplayMember = "Label";
            this.cboNodes.ValueMember = "Value";
            this.cboProductCodes.DisplayMember = "Label";
            this.cboProductCodes.ValueMember = "Value";


            // Country parameters
            cmd = util.SqlConn.CreateCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "proc_parms_countries_for_user";
            cmd.Parameters.Add("@whoAmI", SqlDbType.VarChar).Value = WindowsIdentity.GetCurrent().Name;
            dr = cmd.ExecuteReader();

            /////////////////////////////////////////////////////////////////////////////////////////////////

            var dtCountries = new DataTable();
            dtCountries.Columns.Add("Label");
            dtCountries.Columns.Add("Value");

            //DataRow _countries = dtCountries.NewRow();
            //_countries["country key"] = myBusinessUnit;
            //_countries["country name"] = myDataYear;

            //dtCountries.Rows.Add(_fcst);

            while (dr.Read())
                if (dr["country key"].ToString() != "0" && dr["country key"].ToString() != "1")
                {
                    dtCountries.Rows.Add(dr["country name"].ToString(), dr["country key"].ToString());
                }
            cmd.Parameters.Clear();
            dr.Close();

            this.cboCountries.DataSource = dtCountries;