简体   繁体   中英

how to get all values of selected checkbox in vb.net and set it on string list

I need to get selected items on checkbox and set as string format like (value1,value2,value3) from the checkbox i selected

For Each row As GridViewRow In GridView1.Rows    
    If row.RowType = DataControlRowType.DataRow Then
        Dim CheckRow As CheckBox = (TryCast(row.Cells(1).FindControl("chckSelector"), CheckBox))

        If CheckRow.Checked Then
            Dim scode As String = TryCast(row.Cells(2).FindControl("lblsstorecode"), Label).Text
            lbltest.Text = 'this i want to get the value like this (value1,value2,value3) from checkbox that i selected                
        End If
    End If
Next

Depending on why you are using the GridView control, you might me able to accomplish this easier by using a CheckBoxList instead. In Asp.net what you describe is accomplished very easily with a CheckBoxList as follows:

In .aspx:

<asp:CheckBoxList ID="Itemlst" runat="server" RepeatColumns="1">
    <asp:ListItem Value="">Item 1</asp:ListItem>
    <asp:ListItem Value="">Item 2</asp:ListItem>
    <asp:ListItem Value="">Item 3</asp:ListItem>
</asp:CheckBoxList>

</br>
<asp:Button ID="Button1" runat="server" Text="Button" />
</br>
<asp:TextBox ID="TextBox1" runat="server" Width="400"></asp:TextBox>

Then in the code behind:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim selected = New List(Of ListItem)
    Dim itemcount As Integer
    Dim csvlist As String = ""
    For Each item As ListItem In Itemlst.Items
        If item.Selected Then selected.Add(item)
    Next

    itemcount = selected.Count
    For i = 0 To itemcount - 1
        csvlist = csvlist & selected(i).ToString & ","
    Next
    csvlist = Mid(csvlist, 1, Len(csvlist) - 1)
    TextBox1.Text = csvlist
End Sub

The Windows Forms CheckedListBox would probably work similar if you are developing a desktop application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM