即制作一个wpf,其中一个组合框根据另一个组合框填充.但是,只有一个组合框填充.
这是我的代码如下.
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
this.Load += Form4_Load;
}
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
private void Form4_Load(object sender, EventArgs e)
{
string query = "SELECT * FROM data_organsystem";
fillCombo(comboBox3, query, "name", "id");
comboBox3_SelectedIndexChanged(null, null);
}
private void fillCombo(ComboBox combo, string query, string displayMember, string valueMember)
{
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
combo.DataSource = dt;
combo.DisplayMember = displayMember;
combo.ValueMember = valueMember;
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
int val;
Int32.TryParse(comboBox3.SelectedValue.ToString(), out val);
string query = "SELECT * FROM data_symptom WHERE organ_system_id = " + val;
fillCombo(comboBox4, query, "name", "id");
}
}
}
如果您对如何编辑此代码有任何想法,那将是一个很大的帮助.谢谢!
解决方法:
执行该行的方法comboBox3_SelectedIndexChanged时,您将收到错误
Int32.TryParse(comboBox3.SelectedValue.ToString(), out val);
因为如果在ComboBox中没有选择任何项目,comboBox3.SelectedValue为null,我在您的代码中没有看到您在第一次调用comboBox3_SelectedIndexChanged之前选择了一些项目.
因为没有显示在Form.Load事件处理程序异常中执行的方法comboBox3_SelectedIndexChanged.检查一下:https://*.com/a/3209813/1565525.
这就是为什么你没有得到任何错误
在使用之前,您需要检查SelectedValue是否为null
If(this.comboBox3.SelectedValue is null)
{
this.comboBox4.DataSource = null; //Remove all items if nothing selected
}
else
{
Int32 val= (Int32)this.ComboBox3.SelectedValue;
string query = "SELECT id, name FROM data_symptom WHERE organ_system_id = " + val;
fillCombo(this.comboBox4, query, "name", "id");
}
因为在使用项填充ComboBox时使用DataBinding,所以逻辑上使用SelectedValueChanged事件处理程序
private void comboBox3_SelectedValueChanged(object sender, EventsArgs e)
{
//same code
}