Posted on 2006-08-17 12:15
大大毛 閱讀(425)
評論(0) 編輯 收藏 所屬分類:
ASP.NET
???問題:
???頁面中會遇到實現(xiàn)單選/多選的方法,不幸的是選擇單選或多選是動態(tài)決定的,例如實現(xiàn)投票,需要從vote表中取出數(shù)據(jù),從而決定當(dāng)前的投票是多選還是單選。
???實現(xiàn)這種功能最簡單的方法就是放上兩個panel容器,一個放checkboxlist,一個放radiobuttonlist,根據(jù)檢索到的數(shù)據(jù)實現(xiàn)開關(guān)顯示。
???解決方法:
???使用System.Web.UI.WebControls.ListControl可以輕松的實現(xiàn)動態(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(
"
文本
"
,
"
值
"
);
??
//
或者在這里進行數(shù)據(jù)綁定ctl.DataSource
.
}
???后記:
???ASP.NET中規(guī)定服務(wù)端控件必須放置在Form runat="server"之內(nèi),因此動態(tài)添加時,this.Controls.Add(new Control())是不可以的,必須放入容器中,例如上面的Panel或者頁面的Form中this.form1.Controls.Add...。