第一種方法:
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();
