Shasha
Shasha

Reputation: 3

Checkboxlist Only Select One Item And Deselect The others

I have problem with my checkboxlist to select only one item instead of select multiple items. Can anyone help me to code for it ?

<asp:CheckBoxList class="list-group-item" ID="chkResourceName1" runat="server" AutoPostBack ="true"  OnSelectedIndexChanged ="ResourceName_Click"></asp:CheckBoxList>

Sub ResourceName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Try
      Dim a As Integer = chkResourceName1.Items.Count
        Dim count As Integer = 0

        For i As Integer = 0 To a - 1
            If chkResourceName1.Items(i).Selected = True Then count += 1
        Next

        If count > 1 Then
            For i As Integer = 0 To a - 1
                If chkResourceName1.Items(i).Selected = True Then
                    chkResourceName1.Items(i).Selected = False
                End If
            Next
        End If

    Catch ex As Exception
        attPage.ErrorMessage = DA.GetErrorMessage(1, System.Reflection.MethodBase.GetCurrentMethod.Name.ToString, ErrMsg, ex.Message.ToString, attPage.ActionPage)
        ShowError(attPage.ErrorHeader, attPage.ErrorMessage)
    End Try 
End Sub 

This code results is when the user checked more than one then both of the checked is clear. I want to make If the user click more than one it will clear the previous one and only checked the latest one.

Upvotes: 0

Views: 561

Answers (1)

Precious Uwhubetine
Precious Uwhubetine

Reputation: 3007

Try this, explanations are commented

 Sub ResourceName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
    Dim a As Integer = chkResourceName1.Items.Count
    Dim s As Integer =   chkResourceName1.SelectedIndex
    'Store the currently selected item's index in a variable

    For i As Integer = 0 To a - 1
         chkResourceName1.Items(i).Selected = False
         ' Un check all items
    Next

   chkResourceName1.Items(s).Selected = True
  'check the current item

Catch ex As Exception
    attPage.ErrorMessage = DA.GetErrorMessage(1, System.Reflection.MethodBase.GetCurrentMethod.Name.ToString, ErrMsg, ex.Message.ToString, attPage.ActionPage)
    ShowError(attPage.ErrorHeader, attPage.ErrorMessage)
End Try 

Upvotes: 1

Related Questions