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

  • Thread starter Thread starter Assimalyst
  • Start date Start date
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
 
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
 
Hi,

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

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


Cheers,
 
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,
 
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
 
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,
 
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

**************************************************************+
 
Back
Top