我正在通过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;
}
这个DOES适当地填充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 城市,为什么它填充第四个表而不是初始表?如果您需要更多代码示例以帮助我解决此问题,请与我们联系。非常感谢你!
答案 0 :(得分:1)
如果您填写DataTable
而不是DataSet
,它应该有效,因为您无论如何只选择一个表。
除此之外,我必须承认不知道这种行为的原因。