检查列表框样式单选按钮列表

时间:2010-10-26 08:12:56

标签: vb.net winforms

是否可以有一个单选按钮列表,就像我们有一个选中的列表框一样? 实际上我想将所有选项从数据库加载到列表中,但不希望用户允许检查多个项目。

另外如何阅读它(比如列表的第4项)我想将它的值存储在变量中。

谢谢和最诚挚的问候。 Furqan

1 个答案:

答案 0 :(得分:1)

如果你的意思是ASP.Net RadioButtonList-Control试试这个例子:

aspx(您可以在设计器上配置数据源(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>

Radiobuttonlist允许用户默认只选择一个项目。 所选项目存储在RadioButtonList1.SelectedItem

编辑:由于您已经确认这是Winform问题,因此您需要GroupBox才能允许用户选择一个。

要从数据源动态创建Radiobuttons并将它们添加到Groupbox,请查看我的示例代码:

    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

请记住,您必须用自己的数据对象替换我的数据对象。

相关问题