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