无法在c#.net中动态填充组合框

时间:2016-04-18 07:28:17

标签: c# winforms

我正在编写下面的代码来获取组合框中的数据,但它没有在组合框中显示任何数据,所以请帮助.....下面是我填写组合框的代码..

string qry = "select ctid,city from city order by city";
cmd = new SqlCommand(qry, con);
ds.Clear();
ad = new SqlDataAdapter(qry,con);
ad.Fill(ds);
MessageBox.Show(ds.Tables[0].Rows[1]["city"].ToString());
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "city";
comboBox1.ValueMember = "ctid";
在ad.fill(ds)之后的消息框中的

我可以看到表格中的值,但它没有反映在组合框中...

1 个答案:

答案 0 :(得分:0)

我在我的应用程序中使用了相同的逻辑,区别在于将CommandType属性指定为' Text'和CommandText属性作为查询,在SqlCommand中。

 var sqlDs = new DataSet();
 var sqlComm = new SqlCommand();
        sqlComm.Connection = sqlCon;
        sqlComm.CommandType = CommandType.Text;
        sqlComm.CommandText = query;
        sqlDa = new SqlDataAdapter(sqlComm);
        sqlDa.Fill(sqlDs);

此外,当您指定显示成员和Value成员时,无需在select查询中指定列,它仍然有效。仅在性能基础上,您可以指定列名称。