0

我正在通过 SQL 数据适配器填充 ComboBox,并且遇到了适配器带回四个表计数的问题。这很奇怪,因为数据库中只有三个表,并且它正在用适当的行填充最终表 (ds.Tables[3]) 而不是初始表 (ds.Tables[0])。

以下代码不会填充 ComboBox(注意 cboCities.DataSource(倒数第二行)):

         private void Form1_Load(object sender, EventArgs e)
    {
        // Establishes a connection to the database.
        SqlCeConnection cn = new SqlCeConnection(@"Data Source = C:\Users\user\Desktop\Projects\ParkSurvey WF\ParkSurvey WF\ParkSurvey.sdf; Persist Security Info = False; Password = *");
        cn.Open();
        // Gathering the names of cities from the Cities database to populate cboCities.
        SqlCeCommand cmd = cn.CreateCommand();
        cmd.CommandText = "SELECT CityId, Name FROM Cities ORDER BY Name ASC";
        SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        // Closing the connection and setting the data bindings for cboCities.
        cn.Close();
        cboCities.ValueMember = "CityId";
        cboCities.DisplayMember = "Name";
        cboCities.DataSource = ds.Tables[0];
        cboCities.SelectedIndex = -1;
    }

这确实会适当地填充 ComboBox(再次注意 cboCities.DataSource):

        private void Form1_Load(object sender, EventArgs e)
    {
        // Establishes a connection to the database.
        SqlCeConnection cn = new SqlCeConnection(@"Data Source = C:\Users\user\Desktop\Projects\ParkSurvey WF\ParkSurvey WF\ParkSurvey.sdf; Persist Security Info = False; Password = *");
        cn.Open();
        // Gathering the names of cities from the Cities database to populate cboCities.
        SqlCeCommand cmd = cn.CreateCommand();
        cmd.CommandText = "SELECT CityId, Name FROM Cities ORDER BY Name ASC";
        SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        // Closing the connection and setting the data bindings for cboCities.
        cn.Close();
        cboCities.ValueMember = "CityId";
        cboCities.DisplayMember = "Name";
        cboCities.DataSource = ds.Tables[3];
        cboCities.SelectedIndex = -1;
    }

是什么导致我的 DataAdapter 带回四个表而不是 JUST Cities,为什么它填充第四个表而不是初始表?如果您需要更多代码示例来帮助我解决此问题,请告诉我。非常感谢你!

4

1 回答 1

1

如果您填写 aDataTable而不是 a它应该可以工作,DataSet因为无论如何您只选择一个表格。

除此之外,我必须承认不知道这种行为的原因。

于 2012-05-16T22:01:38.037 回答