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

2024-11-01 00:24:23
推荐回答(2个)
回答1:

  实现方法:
  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());
  }

回答2:

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"; //要显示的字段名
//如果是Web程序的话,加上comboBox1.DataBind();