atabrizi
atabrizi

Reputation: 918

uncheck all items of checkboxlist select in c#

I have this check box in my ascx file :

<asp:CheckBoxList ID="chk" runat="server" RepeatLayout="Table" RepeatDirection="Horizontal" RepeatColumns="1">

i want to have a option to select no options in list. but my checkboxlist choose first option by default.and when i uncheck it and save and load page first option is seleted.

I use this code to unselect but not working:

if (string.IsNullOrEmpty(chk.SelectedValue))
        {
            foreach (ListItem item in chk.Items)
            {
                item.Selected = false;

            }
            chk.SelectedIndex = -1;
        }

I use this code in Page_Load and Page_PreRender of my page. and chk.SelectedValue is null or empty. but first items is cheked

I use this code for bind data to checkboxlist:

 var it = new ListItem {Text = arr1[0], Value = arr1[1];
 chk.Items.Add(it);

Upvotes: 2

Views: 30159

Answers (4)

Enes Kalajac
Enes Kalajac

Reputation: 1

This helped me solve my problem to uncheck all checked items of checkboxlist C# (which is also in the title of this post): uncheck all items of checkboxlist select in c # Thank you Lucas Baum!

        for (int i = 0; i < chk.Items.Count; i++)
        {
            chk.SetItemChecked(i, false);
        }

Upvotes: 0

Lukas Baum
Lukas Baum

Reputation: 12

for (int i = 0; i< chk.Items.Count; i++)
{
     chk.SetItemChecked(i, false);
}
//chk.SelectedIndex = -1;

Upvotes: 0

Azadeen Alasd
Azadeen Alasd

Reputation: 57

Call:

CheckBoxList1.ClearSelection(); 

on pageload.

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460298

Your code is pointless. You are checking if no item is selected(string.IsNullOrEmpty(chk.SelectedValue)), then you want to unselect all.

I assume you want the opposite:

if (chk.SelectedIndex != -1)   // you can also use chk.SelectedValue != "", default is an empty string ("")
{
    //foreach (ListItem item in chk.Items)
    //{
    //    item.Selected = false;
    //}
    chk.SelectedIndex = -1;
}

However, the loop is redundant since SelectedIndex = -1; does the same in one statement.

Upvotes: 4

Related Questions