C# Combo Box SelectedValue Null

本文关键字:Null SelectedValue Box Combo | 更新日期: 2023-09-27 18:19:47

在没有发布我的全部代码(我只是发布了有问题的脚本)的情况下,我遇到了一个问题,看起来很多人都遇到过,但我的问题似乎没有响应其他推荐的修复程序。我在VS2008中使用C#。

基本上,我有一个comboBox,当项init被更改时,它会转到下面的代码。从本质上讲,代码将确定选择了哪个国家(myCountryKey),然后将其作为参数传递给填充后续组合框的存储过程。

奇怪的是,cboCountries的selectedValue属性总是显示为Null。在阅读关于这个问题的文章时,dropdownStyle属性似乎是问题所在,但我按照建议将我的属性更改为DropDownList,但这并不起作用。

因为我经常使用下拉列表,所以我开始玩arond,发现我可以使用SelectedIndex属性,也可以使用GetItemText属性(这就是myCountryKey2和myCountryKey3变量的作用)。然而,我真正想要的是SelectedValue,我以前也做过这样的事情,只是不明白为什么它不起作用。

是否有其他组合框属性我可能意外更改,导致SelectedValue不起作用?

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();
            }
        }

更多代码:

       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();
            }
        }

C# Combo Box SelectedValue Null

我发现了,未绑定的数据再次出现。当我更改代码,将我的国家/地区列表加载到一个数据表中,然后使用该数据表作为我的组合框的源时,一切都很好。

    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;

要使用comboBox.SelectedValue,必须首先设置comboBox.ValueMember

ValueMember(MSDN)

MSDN上的示例演示了如何在数据绑定的情况下使用它。

我理解你的痛苦,请尝试以下

if (myxyzcombo.SelectedItem != null) 
{
 MessageBox.Show(myxyzcombo.SelectedItem.ToString());
 }