Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Asp.net checkboxlist, select or deselect all list items - Part 24

Suggested Videos
Part 17 - Data bind dropdownlist with data from the database
Part 21 - Retrieving selected item text, value and index of the dropdownlist
Part 23 - Asp.net checkboxlist control

In this video we will learn about
1. Selecting a specific ListItem with-in a CheckBoxList control using SelectedValue and SelectedIndex properties
2. Selecting or De-Selecting all ListItems of a CheckBoxList control

To have a ListItem pre-selected, when the page renders, we can do that in the HTML by setting the Selected property to True as shown below.
<asp:ListItem Text="Diploma" Selected="True" Value="1"></asp:ListItem>



This can be programmatically done, using the SelectedValue property as shown below.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        CheckBoxList1.SelectedValue = "1";
    }
}

SelectedIndex property can also be used.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        CheckBoxList1.SelectedIndex = 2;
    }
}



Copy and paste the following HTML and Code in the ASPX and the code behind page
<asp:Button ID="buttonSelectAll" runat="server" Text="Select All" 
    onclick="buttonSelectAll_Click" /> 
&nbsp; 
<asp:Button ID="buttonDeselectAll" runat="server" Text="De-Select All" 
    onclick="buttonDeselectAll_Click" />
<br /><br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
    RepeatDirection="Horizontal">
    <asp:ListItem Text="Diploma" Value="1"></asp:ListItem>
    <asp:ListItem Text="Graduate" Value="2"></asp:ListItem>
    <asp:ListItem Text="Post Graduate" Value="3"></asp:ListItem>
    <asp:ListItem Text="Doctrate" Value="4"></asp:ListItem>
</asp:CheckBoxList>

protected void buttonSelectAll_Click(object sender, EventArgs e)
{
    foreach (ListItem li in CheckBoxList1.Items)
    {
        li.Selected = true;
    }
}

protected void buttonDeselectAll_Click(object sender, EventArgs e)
{
    foreach (ListItem li in CheckBoxList1.Items)
    {
        li.Selected = false;
    }
}

3 comments:

  1. Hello Venkat,
    seems like you are disable the videos from here, Did you do it purposely. I would prefer to watch it here since I follow your notes in the page....
    Thanks

    ReplyDelete
  2. Hai Venkat .....u r very tallented.....thank u r for sharing u r knowledge....
    salute to prigim technologies.

    ReplyDelete
  3. how to get an error message if none of chrckbox list item is selected. .. i mean initially all the list item are unselected if we didn't select any item there should some error msg to check atleast one item dynamically..

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.