创建级联下拉列表(WinForm)

时间:2013-09-18 08:08:36

标签: c# .net winforms

我正在使用下面的代码来填充我的组合框,现在using代码正在运行,我正在使用国家/地区项目获得国家组合框,但如果我在using中编写comboBox1_SelectedIndexChanged代码而不是{ {1}}代码不起作用,为什么会这样?因此,我没有根据所选国家/地区获得州下拉列表,应该如何进行?

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 
    }   
    }

提前致谢

2 个答案:

答案 0 :(得分:0)

在方法comboBox2_SelectedIndexChanged中,您无法创建本地DataTable并将其用作数据源。在您的代码离开using语句后,DataTable将被销毁,而comboBox2将没有数据源。

省略使用声明:

DataTable dt = DBHandling.GetStateDataTable(comboBox1.Text)

您可能只是复制对现有DataTable的引用。那你为什么要处理呢?

答案 1 :(得分:0)

删除comboBox2_SelectedIndexChanged事件,然后双击ComboBox2再次创建事件并检查事件是否被触发。

如果ASP.Net应用程序检查您是否设置了AutoPostBack属性