SQL 数据适配器在仅存在 3 个表时返回 4 个表的计数

本文关键字:返回 数据 存在 SQL 适配器 | 更新日期: 2023-09-27 18:34:19

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

以下代码不会填充组合框(请注意 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,为什么它填充第四个表而不是初始表?如果您需要更多代码示例来帮助我解决此问题,请告诉我。谢谢!

SQL 数据适配器在仅存在 3 个表时返回 4 个表的计数

如果您填写DataTable而不是DataSet,它应该有效,因为无论如何您只选择一个表。

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