combox 的数据源为datatable 时,如何显示数据

来源:百度知道 编辑:UC知道 时间:2024/05/14 09:05:01
语句是这样的:
cbType.DataSource = ds.Tables["type"];
cbType.ValueMember = "TypeID";
cbType.DisplayMember ="TypeName";

做winform程序的时候遇到的问题,已经把数据源绑定为一个datatable对象了,但是好像显示不出来。
语句是这样的

实现方法:
  1、生成datatable,并为combox绑定数据源:
  comboBox1.DataSource = dt1;
comboBox1.DisplayMember = "用户编码";
comboBox1.ValueMember = "ID";
this.comboBox1.SelectedIndex = -1;
  2、在combox的SelectedIndexChanged事件中添加如下方法:
  private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int iCurrentIndex = this.comboBox1.SelectedIndex;
if (iCurrentIndex < 0) return;
  DataRow dr = dt1.Rows[iCurrentIndex];
iID = Int32.Parse(dr["ID"].ToString());
  }

SqlDataAdapter da = new SqlDataAdapter("select * from Customers", "Data Source=.;Initial Catalog=Northwind;Integrated Security=True");

DataSet ds = new DataSet();

da.Fill(ds);

DataTable dt = ds.Tables[0];

comboBox1.DataSource = dt;
comboBox1.DisplayMember = "city"; //要显示的字段名