0

我正在使用下面的代码来填充我的组合框,现在using代码正在运行,并且我正在获取带有国家/地区项目的国家/地区组合框,但是如果我编写using代码而comboBox1_SelectedIndexChanged不是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;
        }

提前致谢

4

2 回答 2

0

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

省略 using 语句:

DataTable dt = DBHandling.GetStateDataTable(comboBox1.Text)

您可能只是在复制对现有 DataTable 的引用。那么为什么要丢弃它呢?

于 2013-09-18T08:19:02.353 回答
0

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

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

于 2013-09-18T09:06:17.433 回答