views:

45

answers:

2

I have a Listview control "lstStudents" and i have added checkboxes inside the List viewControl.I need to add a Select All check box which results in checking all the checkboxes inside the ListView i use the following code but it doesn't work.

  private void chkAll_CheckedChanged(object sender, EventArgs e)
    {
        foreach (Control cont in lstStudents.Controls)
        {
            if (cont.GetType() == typeof(CheckBox))
            {
                (cont as CheckBox).Checked = true;
            }

        }
    }

I'm using c# windows Forms......

+1  A: 

Try this:

private void chkAll_CheckedChanged(object sender, EventArgs e)
{
    foreach (ListViewDataItem item in lstStudents.Items)
    {
        CheckBox cbSelect = item.FindControl("cbSelect") as CheckBox;
        if (cbSelect != null)
        {
            cbSelect.Checked = true;
        } 
     }
 }

Assuming your listview definition goes something like this:

<asp:listview runat="server">
    <itemtemplate>
        <asp:checkbox id="cbSelect" runat="server" />
    </itemtemplate>
</asp:listview>
Naeem Sarfraz
Sorry forgot to mention.I'm using c# windows Forms......
chamara
+2  A: 

You are talking to the dataitem instead of the control itself

    private void chkAll_CheckedChanged(object sender, EventArgs e)
    {
        foreach (ListViewItem item in lstStudents.Items)
        {
            item.Checked = chkAll.Checked;
        }
    }
  • the Checked property is always accessible on a ListViewItem, visible or not.
  • lstStudents.Items returns only ListViewItem

so there is no need for an extra reference validation on these items

Caspar Kleijne
Yup, that's the one.
Hans Passant
Thanks! it's working
chamara