Cannot convert type 'System.Web.UI.Control' to ...

A

Assimalyst

Hi,

I am trying to write some server side validator code in C#. I want to
have a piece of code that can be used by all DropDownLists on a
webform, giving a false value if the SelectedIndex is 0.

Here's the code:

protected void serverValidateCboBx(object source,
ServerValidateEventArgs args)
{
DropDownList dl =
FindControl(((CustomValiator)(source)).ControlToValidate);

if(dl.SelectedIndex == 0)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}

But i get the build error

Cannot implicitly convert type 'System.Web.UI.Control' to
'System.Web.UI.WebControls.DropDownList'

and the FindControl syntax is underlined.

Any suggestions on ways to solve this?

Thanks
 
O

Octavio Hernandez

Hi,

FindControl returns a Control, you need a cast into a DropDownList (if you
know it's gonna be a DroDownList):

DropDownList dl = (DropDownList)
FindControl(((CustomValiator)(source)).ControlToValidate);

Regards - Octavio
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

FindControl returns a Control, not a DropDownList , do this:

DropDownList dl =
FindControl(((CustomValiator)(source)).ControlToValidate) as DropDownList ;


Cheers,
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


The problem with this , is that if the control returned is not a
DropDownList you will get an exception, if you use "as" you will get a null
value , which you can check for after.


cheers,
 
L

Lewis Harvey

Can you not pass in the type and use that to cast it?

Get its parent from the control and then cast it wil that.


Lewis
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You can do so, it's just that a casting does fail with an exception if the
casting can not be done, the "is" operator returns null, which you should
always check in this case anyway.


cheers,
 
O

Octavio Hernandez

Ignacio,

If the CustomValidator is gonna be attached only to DropDownList controls,
you can tell for sure FindControl will return a DropDownList. In that case
the typecast is 100% safe.

Regards - Octavio

**************************************************************+
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top