没有发布我的全部代码(我只是发布了有问题的脚本),我遇到了一个似乎很多人都遇到过的问题,但我的似乎没有响应其他推荐的修复。我在 VS2008 中使用 C#。
基本上我有一个组合框,当项目初始化更改时,它会转到下面的代码。本质上,代码将确定选择哪个国家(myCountryKey),然后将其作为参数传递给填充后续组合框的存储过程。
奇怪的是,cboCountries 的 selectedValue 属性总是显示为 Null。在阅读有关此问题的信息时,似乎 dropdownStyle 属性是问题所在,但我按照建议将我的属性更改为 DropDownList 并且不起作用。
因为我经常使用下拉菜单,所以我开始玩,发现我可以让 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();
}
}