實(shí)現(xiàn)單選/多選動(dòng)態(tài)轉(zhuǎn)化
Posted on 2006-08-17 12:15 大大毛 閱讀(428) 評(píng)論(0) 編輯 收藏 所屬分類: ASP.NET???問(wèn)題:
???頁(yè)面中會(huì)遇到實(shí)現(xiàn)單選/多選的方法,不幸的是選擇單選或多選是動(dòng)態(tài)決定的,例如實(shí)現(xiàn)投票,需要從vote表中取出數(shù)據(jù),從而決定當(dāng)前的投票是多選還是單選。
???實(shí)現(xiàn)這種功能最簡(jiǎn)單的方法就是放上兩個(gè)panel容器,一個(gè)放checkboxlist,一個(gè)放radiobuttonlist,根據(jù)檢索到的數(shù)據(jù)實(shí)現(xiàn)開(kāi)關(guān)顯示。
???解決方法:
???使用System.Web.UI.WebControls.ListControl可以輕松的實(shí)現(xiàn)動(dòng)態(tài)的定制。
protected
?
void
?Page_Load(
object
?sender,?EventArgs?e)?{
?? bool ?isSingle? = ? false ;
??System.Web.UI.WebControls.ListControl?list? = ? null ;
?? if (isSingle)?{
????list? = ? new ?RadioButtonList();
??}? else ?{
????list? = ? new ?CheckBoxList();
??}
?? this .Panel1.Controls.Add(list);
?? if ( ! IsPostBack())?{
????rebindData(list);
??}
}
private ? void ?rebindData(ListControl?ctl)?{
??ctl.Items.Add( new ?ListItem( " 文本 " , " 值 " );
?? //
或者在這里進(jìn)行數(shù)據(jù)綁定ctl.DataSource
.
}
?? bool ?isSingle? = ? false ;
??System.Web.UI.WebControls.ListControl?list? = ? null ;
?? if (isSingle)?{
????list? = ? new ?RadioButtonList();
??}? else ?{
????list? = ? new ?CheckBoxList();
??}
?? this .Panel1.Controls.Add(list);
?? if ( ! IsPostBack())?{
????rebindData(list);
??}
}
private ? void ?rebindData(ListControl?ctl)?{
??ctl.Items.Add( new ?ListItem( " 文本 " , " 值 " );
?? //


}
???后記:
???ASP.NET中規(guī)定服務(wù)端控件必須放置在Form runat="server"之內(nèi),因此動(dòng)態(tài)添加時(shí),this.Controls.Add(new Control())是不可以的,必須放入容器中,例如上面的Panel或者頁(yè)面的Form中this.form1.Controls.Add...。