2008年10月28日 星期二

把多個RadioButtonList設為相同Group

問題: 如果頁面上有多組RadioButtonList,要做到這幾組RadioButtonList間都只能單選,例如:
50cc機車 125cc機車 150cc以上機車

休旅車 跑車 房車

如果上下兩排各是一個RadioButtonList如何讓他們都屬與同一group
當然,我們可以只用html的radio button做到,只要name屬性設為一樣。但是如果想透過程式動態產生那些選項,RadioButtonList還蠻好用的。可惜它沒有name or groupname這個property可用!

我的作法是做一個含RadioButtonList的UserControl:

Partial Class UCRadioBtnList
Inherits System.Web.UI.UserControl

Private _GroupName As String

'提供設定RadioButton項目
Public WriteOnly Property Items() As String()
Set(ByVal value As String())
Dim ItemTemp As ListItem

For Each v As String In value
ItemTemp = New ListItem(v)
Me.RadioButtonList.Items.Add(ItemTemp)
Next
End Set End Property

'提供設定RadioButtonList的RroupName
Public Property GroupName() As String
Get
Return Me._GroupName
End Get
Set(ByVal value As String)
Me._GroupName = value
'把GropuName存在ViewState中,預防postback時消失
If IsNothing(Me.ViewState("GroupName")) Then
Me.ViewState("GroupName") = value
End If
End Set
End Property

'註冊一行會呼叫 function SetSameGroup( )的script到畫面
Private Sub SetSameGroup()
Dim StrScript As String

StrScript = "SetSameGroup('" & Me.ClientID & "$RadioButtonList','" &
Me.ViewState ("GroupName") & "');" & vbNewLine
ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType(), Me.RadioButtonList.ClientID, StrScript, True)
End Sub

'畫面載入時都在註冊一次script(因為script在postback後就會自動消失)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.SetSameGroup()
End Sub

End Class


//javascript


function SetSameGroup(paramOldName, paramGroupName) {
var ObjArray = document.getElementsByTagName("Input");
var StrTemp;
for (i = 0; i < ObjArray.length; i++) {
if(ObjArray[i].type == "radio" && ObjArray[i].name == paramOldName) {
StrTemp = ObjArray[i].parentNode.innerHTML.replace(paramOldName, paramGroupName);
ObjArray[i].parentNode.innerHTML = StrTemp;
}
}
}


使用這個UserControl的畫面的.vb檔

Dim ArrayListSource1 As String() = {"aa", "bb", "cc", "dd"}
Dim ArrayListSource2 As String() = {"ee", "ff", "gg", "hh"}

Me.UCRadioBtnList1.Items = ArrayListSource1 '加入選項
Me.UCRadioBtnList2.Items = ArrayListSource2
Me.UCRadioBtnList1.GroupName = "sss" '設定GroupName
Me.UCRadioBtnList2.GroupName = "sss"

By Felix

沒有留言: