Home > Net >  How can I show the text of the only "Checked" checkboxes into a Msgbox in Vb.net?
How can I show the text of the only "Checked" checkboxes into a Msgbox in Vb.net?

Time:07-26

I am using vb.net and this is my problem. Suppose I have 3 checkboxes.

  • Pizza
  • Ice cream
  • Fries

What I want to do is when I click the "Pizza" and "Fries", the Msgbox will only show me the text on the "checked" checkboxes:

  • Pizza
  • Fries

And not include the one checkbox that is unchecked. Any help will be appreciated!!!

CodePudding user response:

MessageBox.Show(String.Join(", ",
                            Controls.OfType(Of CheckBox)().
                                     Where(Function(cb) cb.Checked).
                                     Select(Function(cb) cb.Text)))

This assumes that all CheckBoxes are on the form directly and that they are the only CheckBoxes on the form. If they are in some other child container, you would use the Controls collection of that container. If there may be other CheckBoxes in the same container, you could add a Panel and put just these CheckBoxes in it. If you prefer your LINQ with query syntax rather than function syntax:

MessageBox.Show(String.Join(", ",
                            From cb In Controls.OfType(Of CheckBox)()
                            Where cb.Checked
                            Select cb.Text))

CodePudding user response:

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AddHandler chkFiries.CheckedChanged, AddressOf checkedChanged
        AddHandler chkIcecream.CheckedChanged, AddressOf checkedChanged
        AddHandler chkPizza.CheckedChanged, AddressOf checkedChanged
    End Sub
    Private Sub checkedChanged(sender As Object, e As System.EventArgs)
        Dim checkedNames As String
        For Each ctrl As Control In Me.Controls
            If TypeOf ctrl Is CheckBox Then
                Dim chkbox = TryCast(ctrl, CheckBox)
                If chkbox.Checked = True Then
                    checkedNames  = chkbox.Text & ","
                End If
            End If
        Next

        MessageBox.Show(checkedNames)
    End Sub
  • Related