用DataReader在comboBox中显示name,取值id:

用DataReader在comboBox中显示name,取值id:

定义ItemObject

class ItemObject

{

public int id;

public string name;

 

public ItemObject(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 ()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值