我在组合框中有3个单选按钮。我编写了我认为正确的内容,但该事件仅适用于一个单选按钮。例如,如果单击rdbServiceStandard,则显示rbServicePermanent的值为'P',它应显示'S',有时它根本不会触发。我想我的问题是,如果我正确编码以从单选按钮检索值是一个组合框。非常感谢
groupbox
gbxServiceLevel
单选按钮
rdbServiceStandard
rbServicePermant
rdbServiceRapid
变量保持值
rbServiceLevel
Private Sub gbxServiceLevel_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gbxServiceLevel.Enter
If rdbServiceStandard.Checked Then
rbServiceLevel = "S"
ElseIf rdbServiceRapid.Checked Then
rbServiceLevel = "R"
ElseIf rdbServicePermanent.Checked Then
rbServiceLevel = "P"
End If
MessageBox.Show(rbServiceLevel)
End Sub
答案 0 :(得分:2)
If CType(sender, RadioButton).Checked Then
Select Case Ctype(sender,radiobutton).Name
Case "rdbServiceStandard"
If rdbServiceStandard.Checked Then rbServiceLevel = "S"
Case "rdbServiceRapid"
If rdbServiceRapid.Checked Then rbServiceLevel = "R"
Case Else 'rdbServicePermanent
If rdbServicePermanent.Checked Then rbServiceLevel = "P"
End Select
MessageBox.Show(rbServiceLevel)
End If
问题是选项(无线电)按钮组获得CheckChanged事件两次:一次是旧选择是UNCHECKED,一次是CHECKED,所以只捕获用户选择的行为选项,在检查发件人状态时响应。如果没有CHECK测试,您将获得两次msgbox。
您可以使用Tag
属性来缩短代码。将eacd radiobutton的Tag属性设置为相应的代码(例如rdbServiceStandard
将为“S”)。那么代码就是:
' this is just to prevent 2 CType statements
Dim thisRB As RadioButton = CType(sender, RadioButton).Checked
If rb.Checked Then
rbServiceLevel = thisRB.Tag
End If
其次,如果I first enter the form and click the first option rdbServiceStandard, which is default, it shows 'S' which is fine
:如果你必须点击第一个选项来选择它,那么它不是默认选项 - 默认选项是开始时已经选择的选项表格打开。
第三,如果第一个确实是默认值,则在加载表单时将触发CheckChanged事件,并且VB / NET将默认值设置为已选中。这通常没什么大不了的 - 它只是将rbServiceLevel
设置为默认值。但是如果事件中的动作代码像MsgBox一样,它也会运行。
答案 1 :(得分:1)
我发现操作radiobuttons checkedchanged事件比使用Groupbox的Enter事件更容易:
Private Sub RadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles rdbServiceStandard.CheckedChanged, rdbServiceRapid.CheckedChanged, rdbServicePermanent.CheckedChanged
Select Case Ctype(sender,radiobutton).Name
Case "rdbServiceStandard"
If rdbServiceStandard.Checked Then rbServiceLevel = "S"
Case "rdbServiceRapid"
If rdbServiceRapid.Checked Then rbServiceLevel = "R"
Case Else 'rdbServicePermanent
If rdbServicePermanent.Checked Then rbServiceLevel = "P"
End Select
MessageBox.Show(rbServiceLevel)
End Sub