How to traverse checkbox in Asp.net

Source: Internet
Author: User

During development, we often need to determine the number of checkboxes selected and make a summary.
First, the most common is to directly traverse the checkbox that exists in the page. The basic idea is to traverse all the controls in the page and then determine whether the control type is system. web. UI. webcontrols. the checkbox is fine. The Code is as follows:

Foreach (control CT in form1.controls)
{
If (Ct. GetType (). tostring (). Equals ("system. Web. UI. webcontrols. checkbox "))
{

Checkbox cb = (checkbox) CT;
CB. Checked = true;

}
}

The second is that we often use the gridview control to display data. We often add a column of checkbox to control selection and select all. How can we traverse the checkbox in the gridview? I made a simple example here

You can see that after you click Select All, all the checkboxes in the gridview are selected as follows.

Protected void checkbox#checkedchanged (Object sender, eventargs E)
{
Int I;
If (checkbox) sender). Checked)
{
For (I = 0; I <gridview1.rows. Count; I ++)
{
(Checkbox) gridview1.rows [I]. findcontrol ("checkbox2"). Checked = true;
}
}
Else
{
For (I = 0; I <gridview1.rows. Count; I ++)
{
(Checkbox) gridview1.rows [I]. findcontrol ("checkbox2"). Checked = false;
}
}
}
First, add the checkbox‑checkedchanged event to the checkbox1, that is, the all-selected checkbox. Note that many of your friends did this but did not succeed, because the atuopostback of checkbox must be set to true, otherwise, the status will not change.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.