2012-01-21 195 views
1

我的代码有问题。它正确地显示了组合框的内容,但每当数据为空时,它就不会返回为空。基于组合框填充文本框和组合框 - Winforms

我的第一个组合框是客户端名称,当我单击连接到数据库的组合框中的客户端名称后,应将他的性别放在组合框中。

*注意,这是编辑表单所以我知道该怎么做的就是更新

这是正确的,如果该字段输入,但如果它不是存储在组合框中的值没有被该字段改变为空

例如:

选择客户端1 * 显示他的性别在组合框(前女) 选择客户端2 *性别是女性跆拳道? (鉴于用户忘记把他的性别)

***所以我的问题是,如果该字段为空,我的组合框将不会为空,而是保留我以前使用的值的值。

这是我的代码。 ** combobox1是客户名称列表,combobox2是性别列表

private void BindControls() // function to bind the database to the comboBox 
     { 
      comboBox1.DataSource = _db.Client(); 
      comboBox1.DisplayMember = "client"; //client names are shown in the combobox 
     } 


private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      comboBox2.SelectedItem = ((DataRowView)comboBox1.SelectedItem).Row["gender"].ToString(); //the value of gender in database is put in the combobox2 
     } 

@@在我的性别组合框(combobox2)的项目不绑定到DATABSE我只是手动将值出现在项目组合框的属性(这是视觉工作室的一个功能)

非常感谢!只是问我是否不清楚,我会添加一些细节。

回答

2

尝试使用类似:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
     String genderString = ((DataRowView)comboBox1.SelectedItem).Row["gender"].ToString(); 

     if (!String.IsNullOrEmpty(genderString)) 
     { 
      comboBox2.SelectedItem = ((DataRowView)comboBox1.SelectedItem).Row["gender"].ToString(); //the value of gender in database is put in the combobox2 
     } 
     else 
     { 
      comboBox2.SelectedIndex = -1; 
     } 
} 

它只是设置组合框回到未选中状态,如果性别是一个空字符串(我怀疑null值不应该出现,因为这列的值)。