一、DropDownList:
1、選項值保存到數據庫:
Hashtable ht=new Hashtable();//這裏用Hashtable
ht.Add("字段名",DropDownListID.SelectedItem.Text.ToString());//保存選項Text
ht.Add("字段名",DropDownListID.SelectedItem.Value.ToString());//保存選項Value
2、選項值由數據庫綁定到DropDownList:
首先DropDownListID.ClearSelection();//清除選項
DropDownListID.Items.FindByText(dr["字段名"].ToString()).Selected = true;//選項Text
DropDownListID.Items.FindByValue(dr["字段名"].ToString()).Selected = true;//選項Value
二、RadioButtonList:
1、選項值保存到數據庫(同DropDownList):
Hashtable ht=new Hashtable();//這裏用Hashtable
ht.Add("字段名",RadioButtonListID.SelectedItem.Text.ToString());//保存選項Text
ht.Add("字段名",RadioButtonListID.SelectedItem.Value.ToString());//保存選項Value
2、選項值由數據庫綁定到RadioButtonList
string SelectItem = dr["字段名"].ToString();//將數據庫中的選項值從DataRow中讀出賦給變量SelectItem
for (int i = 0; i < RadioButtonListID.Items.Count; i++)
{//用for循環判斷那項被選種
if (RadioButtonListID.Items[i].Text == SelectItem)RadioButtonListID.Items[i].Selected = true;
}
三、CheckBoxList:
1、選項值保存到數據庫
string SelectItem = "";//聲明一個變量來接受選項
for (int i = 0; i < CheckBoxListID.Items.Count; i++)
{//用for循環將所有選項用","隔開連接起來
if (CheckBoxListID.Items[i].Selected)
{
SelectItem = SelectItem + CheckBoxListID.Items[i].Value + ",";//選項後加","隔開
}
}
ht.Add("字段名",SelectItem.ToString());
2、選項值由數據庫綁定到CheckBoxList
string SelectItem = dr["字段名"].ToString();
string[] arrStr = SelectItem.Split(',');//字段是以","隔開
foreach (string str in arrStr)
{
for (int i = 0; i <CheckBoxListID.Items.Count; i++)
{
if (this.CheckBoxListID.Items[i].Value == str)
{
this.CheckBoxListID.Items[i].Selected = true;
}
}
}
=================================================
1.把數據綁定到CheckBoxList中
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlConnection con = GetDBCon.GetCon();
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from admin", con);
DataSet ds = new DataSet();
sda.Fill(ds,"admin");
this.CheckBoxList1.DataSource = ds.Tables[0];
this.CheckBoxList1.DataTextField = "username";//綁定的字段名
this.CheckBoxList1.DataValueField = "userid";//綁定的值
this.CheckBoxList1.DataBind();
}
}
2.循環讀取出來
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
this.Lab2.Text = "";
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (this.CheckBoxList1.Items[i].Selected)
{
this.Lab2.Text = this.Lab2.Text+CheckBoxList1.Items[i].Text+".";
}
}
}