Check List Box style Radio Button list
Is it possible to have a Radio button list, like we have a checked List box? Actually I want to load all the options from database to 开发者_StackOverflow社区the list but do not want user to allow to check more than one item.
Also how to read it (say item 4 of the list) I want to store its value in the variable.
Thanks and best regards. Furqan
If you mean the ASP.Net RadioButtonList-Control try this example:
aspx(you can configure the datasource on the designer(show smart Tag):
<asp:RadioButtonList ID="RadioButtonList1" runat="server" DataSourceID="SqlDataSource1"
DataTextField="ClaimStatusName" DataValueField="idClaimStatus">
</asp:RadioButtonList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RM2ConnectionString %>"
SelectCommand="SELECT [idClaimStatus], [ClaimStatusName] FROM [dimClaimStatus]">
</asp:SqlDataSource>
A Radiobuttonlist allows user to select only one item by default.
The selected Item is stored in RadioButtonList1.SelectedItem
.
EDIT: As you have clairified now that it's a Winform issue, you need a GroupBox to allow user only to select one.
To create the Radiobuttons dynamically from datasource and add them to the Groupbox, have a look at my samplecode:
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim allStatus As DataSet2.StatusDataTable = New DataSet2TableAdapters.StatusTableAdapter().GetData()
For i As Int32 = 0 To allStatus.Rows.Count - 1
Dim status As DataSet2.StatusRow = allStatus(i)
Dim rb As New RadioButton()
rb.Text = status.ClaimStatusName
rb.Tag = status.idClaimStatus
rb.Location = New Point(Me.GroupBox1.Location.X + 5, Me.GroupBox1.Location.Y + i * rb.Height)
AddHandler rb.CheckedChanged, AddressOf RBCheckedChanged
Me.GroupBox1.Controls.Add(rb)
Next
Me.GroupBox1.Visible = allStatus.Rows.Count > 0
If allStatus.Rows.Count > 0 Then
Dim width, height As Int32
Dim lastRB As Control = Me.GroupBox1.Controls(GroupBox1.Controls.Count - 1)
width = lastRB.Width + 20
height = lastRB.Height
Me.GroupBox1.Size = New Size(width, allStatus.Rows.Count * height + 20)
End If
End Sub
Private Sub RBCheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim source As RadioButton = DirectCast(sender, RadioButton)
Dim checkedRB As RadioButton = getCheckedRadioButton(Me.GroupBox1)
'source and checkedRB are the same objetcs because we are in CheckedChanged-Event'
'but getCheckedRadioButton-function works from everywhere'
End Sub
Private Function getCheckedRadioButton(ByVal group As GroupBox) As RadioButton
For Each ctrl As Control In group.Controls
If TypeOf ctrl Is RadioButton Then
If DirectCast(ctrl, RadioButton).Checked Then Return DirectCast(ctrl, RadioButton)
End If
Next
Return Nothing
End Function
Remember that you must replace my data objects with yours.
精彩评论