1
protected void Page_Load(object sender, EventArgs e)2

{3
DataSet ds = new DataSet();4
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Questions; Integrated security=true;");5
SqlDataAdapter da = new SqlDataAdapter("select * from QuestionTable", conn);6
da.Fill(ds, "QuestionTable");7

8
da = new SqlDataAdapter("select * from QuestionOpiton", conn);9
da.Fill(ds, "QuestionOpiton");10

11
if (ds != null && ds.Tables["QuestionTable"].Rows.Count > 0)12

{13
int i = 0;14
HiddenField1.Value = "";15
foreach (DataRow row in ds.Tables["QuestionTable"].Rows)16

{17
DataRow[] rows = ds.Tables["QuestionOpiton"].Select("QuestionId = " + row["QuestionId"].ToString() + "");18

19
if (row["QuestinType"].ToString().Equals("1"))20

{21
Label labl = new Label();22
labl.Text = row["QuestionContent"].ToString();23
div1.Controls.Add(labl);24
CheckBoxList chkbox = new CheckBoxList();25

26
string clientid = "chk" + i.ToString();27
HiddenField1.Value += clientid + ",";28
chkbox.ID = clientid;29

30
foreach (DataRow row2 in rows)31

{32
ListItem item = new ListItem();33

34
item.Text = row2["QuestionOpitonType"].ToString() + ": " + row2["QuestionOpitonName"].ToString();35
item.Value = row2["QuestionOptionId"].ToString();36
chkbox.Items.Add(item);37
div1.Controls.Add(chkbox);38
if (IsPostBack) break; //关键在这里,39
//因为点击按钮要再次添加才能再次取到控件,40
//所以再添加 一次后就让他跳出循环41
//这样就不会在点击按钮后这个CheckBoxList 里有重复项了42
43
}44
}45
i++;46
}47
if (!IsPostBack)48

{49
if (HiddenField1.Value.IndexOf(",") > -1)50

{51
HiddenField1.Value = HiddenField1.Value.Remove(HiddenField1.Value.Length - 1);52
}53
}54
}55

56

57
}58

59

60

61
protected void Button1_Click(object sender, EventArgs e)62

{63
string strChkBoxNams = HiddenField1.Value;64
string strValue = string.Empty;65
if (strChkBoxNams.IndexOf(",") > 0)66

{67
string[] chkBox = strChkBoxNams.Split(',');68
foreach (string chk in chkBox)69

{70
if (!string.IsNullOrEmpty(chk))71

{72
CheckBoxList chkBoxList = (CheckBoxList)FindControl(chk);73

74
foreach (ListItem item in chkBoxList.Items)75

{76
if (item.Selected)77

{78
strValue += item.Value + ",";79
}80
}81
}82
}83
strValue = strValue.Remove(strValue.Length - 1);84
}85
else if (strChkBoxNams.Length > 0)86

{87
CheckBoxList chkBoxList = (CheckBoxList)FindControl(strChkBoxNams);88

89
foreach (ListItem item in chkBoxList.Items)90

{91
if (item.Selected)92

{93
strValue += item.Value + ",";94
}95
}96
strValue = strValue.Remove(strValue.Length - 1);97
}98
Response.Write(strValue);99
}
浙公网安备 33010602011771号