El Sande
El Sande

Reputation: 30

How do I checkbox.Checked using a variable of type "Control"?

I'm trying to store the ID of CheckBox in a Control variable and then to test it if the CheckBox.Checked is true or false, here is my code:

    Control checkbox1 = FindControl(foo);
    if (checkbox1.Checked)
    {

    }

And I got this error:

'System.Web.UI.Control' does not contain a definition for 'Checked' and no extension method 'Checked' accepting a first argument of type 'System.Web.UI.Control' could be found (are you missing a using directive or an assembly

Upvotes: 0

Views: 573

Answers (3)

शेखर
शेखर

Reputation: 17614

You should use like this

CheckBox checkbox1 = FindControl(foo) as CheckBox;
if(checkbox1!=null)
{
    if (checkbox1.Checked)
    {
         //write your code here
    }
 }

Upvotes: 1

Jameem
Jameem

Reputation: 1838

If your control is placed inside gridview..Try looping through gridview and find the control and check it..

foreach (GridViewRow i in Gridview1.Rows)
{
    CheckBox checkbox1 = (CheckBox)FindControl(foo);
    if (checkbox1.Checked)
    {

    }
}

I am guessing Checkbox is inside gridview..You can do this in other cases also..

Upvotes: 0

John Saunders
John Saunders

Reputation: 161773

CheckBox checkbox1 = (CheckBox)FindControl(foo);
if (checkbox1.Checked)
{

}

You have to cast to the correct type. It doesn't happen by magic in .NET.

Upvotes: 1

Related Questions