创建级联下拉列表(WinForm)
本文关键字:WinForm 下拉列表 级联 创建 | 更新日期: 2023-09-27 18:31:49
我正在使用以下代码来填充我的组合框,现在using
代码可以正常工作,并且我正在获得带有国家/地区项目的国家/地区组合框,但是如果我用comboBox1_SelectedIndexChanged
编写using
代码,那么using
代码不起作用,为什么会这样? 正因为如此,我没有根据所选国家/地区获得状态下拉列表,应该怎么做?
public partial class RegPatient : Form
{
DBHandling db = new DBHandling();
string cmbvalue="";
public RegPatient()
{
InitializeComponent();
using (DataTable dt = DBHandling.GetCountryDataTable())
{
comboBox1.DataSource = new BindingSource(dt, null);
comboBox1.DisplayMember = "CountryName"; //column to show in comboBox
comboBox1.ValueMember = "Code";
}//here the table is disposed
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//using code not working here
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
using (DataTable dt = DBHandling.GetStateDataTable(comboBox1.Text) )
{
// contine using dt
comboBox2.DataSource = new BindingSource(dt, null);
comboBox2.DisplayMember = "ProvinceName";
}//here the table is disposed
}
}
用于获取数据表国家/地区和州/地区的代码
public static DataTable GetCountryDataTable()
{
DataTable countryTable = new DataTable();
using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sonorepo.mdb")) //use your conn. string here
{
using (OleDbDataAdapter da = new OleDbDataAdapter(@"SELECT CountryName, Code FROM Country", con))
da.Fill(countryTable);
}
return countryTable;
}
public static DataTable GetStateDataTable(string countryCode)
{
DataTable stateTable = new DataTable();
using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sonorepo.mdb"))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(@"SELECT ProvinceName FROM Province where Country='" + countryCode + "'", con))
da.Fill(stateTable);
}
return stateTable;
}
提前致谢
在方法comboBox2_SelectedIndexChanged中,不能创建本地 DataTable 并将其用作数据源。代码离开 using 语句后,数据表将被销毁,使 comboBox2 没有数据源。
省略 using 语句:
DataTable dt = DBHandling.GetStateDataTable(comboBox1.Text)
您可能只是复制对现有数据表的引用。那你为什么要处理它呢?
删除 comboBox2_SelectedIndexChanged
事件并双击 ComboBox2 以再次创建事件并检查事件是否被触发。
如果其 ASP.Net 应用程序,请检查是否已设置AutoPostBack
属性