I have some check boxes.I want to print text of selected check boxes of the page.Code which I wrote is neither giving error nor giving correct output .Please help me .Here is the code

protected void btnSelect_Click1(object sender, EventArgs e)
    {
        string strchkSelected = "";

        foreach (Control ctl in Page.Controls)
        {


            if (ctl is CheckBox)
            {
                if(((CheckBox)ctl).Checked)
                    {
                        strchkSelected += ((CheckBox)ctl).Text + " ";
                     }
            
            }

        }

        Response.Write(strchkSelected);

    }

Recommended Answers

All 5 Replies

hi aravind,
can u be more specific.u are wiritng a code to print the text of a check box .where u r using this checkbox

Here is your mistake,

For Each ctl In Page.Controls(1).Controls

page.controls(1) will give you HtmlForm control and
page.controls(1).controls wil give you collection of controls in Your Form.

Hi Bushii,
I tried your code but it is also printing nothing.

I am using three check boxes .I want to print text of check boxes in the same page
when I click the button.

Hi Kishore,

first of all sorry that i have sent u a code in VB, secondly its just a suggestion for u plz try to debug ur code. during debugging u learn a lot tht where u r doing mistake, it seems u don't do it.

Now, its a working code but i m simply assuming ur checkboxes are in the form tag directly not in any HtmlTable correct?. Now if u r using it in HtmlTable or in any other control this code will again not work the simple solution is please follow the same strategy which i have followed for "HTMLFORM" Control.Best of luck

protected void btnSelect_Click1(object sender, EventArgs e)
{
        string strchkSelected = "";
        int i = Page.Controls.Count;

        foreach (Control ctl in Page.Controls)
        {
            if (ctl is HtmlForm)
            {
                for (int count = 0; count < ctl.Controls.Count; count++)
                {
                    if (ctl.Controls[count] is CheckBox)
                    {
                        if (((CheckBox)ctl.Controls[count]).Checked)
                        {
                            strchkSelected += ((CheckBox)ctl.Controls[count]).Text + " ";
                        }

                    }
                }

            }

        }

        Response.Write(strchkSelected);
    }   

}

Thaks Bushii,
Your code is working properly.But I have a doubt that .Each time one control [ctl] from Page.Controls is checked then why You have taken anthoer for loop where you have checked count<ctl.Controls.Count.Why have you written this code.That code is confusing me.Please explain.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.