Winform_ComBox三种赋值方式
第一种方法:
datatable dt =
new
datatable();
dt.columns.add(
"name"
);
dt.columns.add(
"value"
);
datarow dr = dt.newrow();
dr[0] =
"活动"
;
dr[1] =
"1"
;
dt.rows.add(dr);
datarow dr1 = dt.newrow();
dr1[0] =
"生活"
;
dr1[1] =
"2"
;
dt.rows.add(dr1);
this
.combobox1.datasource = dt;
this
.combobox1.displaymember =
"name"
;
this
.combobox1.valuemember =
"value"
;
//调用方法:
//string
_value = combobox1.selectedvalue.tostring();
第二种:
//首先添加一个comboboxitem类
public
class
comboboxitem
{
private
string
_text =
null
;
private
object
_value =
null
;
public
string
text
{
get
{
return
this
._text;
}
set
{
this
._text = value;
}
}
public
object
value
{
get
{
return
this
._value;
}
set
{
this
._value = value;
}
}
public
override
string
tostring()
{
return
this
._text;
}
}
comboboxitem newitem =
new
comboboxitem();
newitem.text =
"男"
;
newitem.value =
"1"
;
comboboxitem newitem1 =
new
comboboxitem();
newitem1.text =
"女"
;
newitem1.value =
"0"
;
com_sex.items.add(newitem);
com_sex.items.add(newitem1);
comboboxitem sex_item = (comboboxitem)com_sex.selecteditem;
int
com_sex_value = convert.toint32(sex_item.value);
string
_name = sex_item.text;
第三种:
//首先添加一个setcls类
public
class
setcls
{
private
string
id;
private
string
name;
public
setcls(
string
pid,
string
pname)
{
this
.id =pid;
this
.name =pname;
}
public
string
pid
{
get
{
return
id;}
}
public
string
pname
{
get
{
return
name;}
}
}
// 赋值方法:(使用arraylist 要先引用命名空间using system.collections;)
arraylist lists =
new
arraylist();
lists .add(
new
setcls (
"1"
,
"活动"
));
lists .add(
new
setcls (
"2"
,
"生活"
));
this
.combox.displaymember =
"pid"
;
this
.combox.valuemember =
"pname"
;
this
.combox.datasource = lists;
string
com_sex_value = combox.selectedvalue.tostring();
我用dataset填充的数据库中的内容(我这个是直接赋值,并不像上面三个添加值给combox)
dataset ds_zubie =
new
dataset();
da =
new
sqldataadapter(sql_zubie, publicdb.dbzbw);
da.fill(ds_zubie,
"zubie"
);
com_paidan.datasource = ds_zubie.tables[
"zubie"
].defaultview;//绑定数据源
com_paidan.valuemember =
"zubie_id"
;//赋值value
com_paidan.displaymember =
"zubie_name"
;//赋值显示名称
string
com_zubie_id = com_paidan.selectedvalue.tostring();