0

How do I make one of the items in my checkboxlist automatically selected upon page load? The items in my checkboxlist come from a SQL DB and I want one of the fields to be automatically selected. I have found simple solutions to this question if I was not retrieving my checkboxlist items from a Database, but I am having trouble figuring out how to do this based on my situation. Any help would be greatly appreciated.

Here is my code for my 2 relevant pages:

ALCounties.aspx.vb

Imports System.Collections.Generic

Partial Class ALCounties
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim chkValues As Dictionary(Of String, Double) = _
        New Dictionary(Of String, Double)


    For Each Item As ListItem In CheckBoxList1.Items
        If (Item.Selected) Then
            If (Not Item.Value Is Nothing And Not String.IsNullOrEmpty(Item.Value())) Then
                chkValues(Item.Text.ToString) = Convert.ToDouble(Item.Value)
            Else
                chkValues(Item.Text.ToString) = 0
            End If

        End If
    Next Item

    Session("CheckedItems") = chkValues
    Response.Redirect("Cart.aspx")
End Sub
End Class

ALCounties.aspx

<asp:CheckBoxList ID="CheckBoxList1" runat="server" 
                DataSourceID="SqlDataSource1" DataTextField="AL_County" 
                DataValueField="AL_Fee">
            </asp:CheckBoxList>
       </div>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server"        ConnectionString="<%$ ConnectionStrings:advancedleadsConnectionString %>" 
                SelectCommand="SELECT [AL_Fee], [AL_County]  FROM [AL]">   </asp:SqlDataSource>

        <p>&nbsp;</p>
        <p>
        <asp:Button ID="Button1" runat="server" Text="Submit" />
        </p>

1 Answer 1

1

I would add a handler for the OnDataBound event of the CheckBoxList. In this handler you can foreach over the .Items property of the control and evaluate wahtever criteria you have for the item to be selected.

Sign up to request clarification or add additional context in comments.

1 Comment

kmcc049, thank you for your quick reply to my question. I am very new to asp.net and your reply is just a little bit above my understanding. I am learning slowly, but surely, and unsure about what some of the terminology means. Most everything I have done and learned has been through online reading and research, reviewing similar questions, and asking questions. With all that said, I am unsure of exactly what your answer means for me to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.