标签:
用DataReader在comboBox中显示name,取值id:
定义ItemObject类
classItemObject
{
public int id;
public string name;
publicItemObject(int id,string name)
{
this.id=id;
this.name =name;
}
public override string ToString()
{
return name;
}
}
1、实例化对象,加载数据
ItemObject[] io = new ItemObject[3]; io[0] = new ItemObject("2010", "1"); io[1] = new ItemObject("2011", "2"); io[2] = new ItemObject("2012", "3"); combobox.Items.AddRange(io);
取值:
((ItemObject )this.comboBox1 .SelectedItem).id
2、加载数据
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn=new SqlConnection ();
conn.ConnectionString ="Data Source=.\\SQLEXPRESS;Initial Catalog=MyQQ;User Id=sa;Pwd=123";
string sql="select userid,userName from users";
conn.Open ();
SqlCommand comm=new SqlCommand (sql,conn);
SqlDataReader dr=comm.ExecuteReader();
if(dr.HasRows )
{
ItemObject item;
while(dr.Read ()){
item=newItemObject (Convert.ToInt32 (dr["userId"]),dr["userName".ToString ()]);
this.comboBox1.Items.Add(kv);
}
}
}
取值:
((ItemObject )this.comboBox1 .SelectedItem).id
3 、DataAdapter在comboBox中显示name,取值id
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn=new SqlConnection ();
conn.ConnectionString ="Data Source=.\\SQLEXPRESS;Initial Catalog=MyQQ;User Id=sa;Pwd=123";
string sql="select * from users";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "users");
this.comboBox1 .DataSource =ds.Tables ["users"]; //为comboBox指定数据源
this.comboBox1.DisplayMember = "nickname"; //为comboBox指定显示的字段名
this.comboBox1.ValueMember = "id"; //为comboBox指定取值的字段名
}
取值:
this.comboBox1 .SelectedValue .ToString ()
s
用DataReader在comboBox中显示name,取值id:
标签:
原文地址:http://www.cnblogs.com/hackdz/p/4520822.html