首页 > 其他 > 详细

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

时间:2015-05-21 22:27:58      阅读:312      评论:0      收藏:0      [点我收藏+]

DataReadercomboBox中显示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 、DataAdaptercomboBox中显示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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!