Wednesday, March 28, 2012

System.InvalidCastException: Specified cast is not valid.

i'm retrieving data with Repeater from Sql Database. i have color colums in the table.. such as color1, color2, color3, color4 and columns type Nvarchar.

i implemented below the function to get team colors instead of characters in the table cells

---- function -----

string Team_Colours(string color)
{
switch (color)
{
case "WHITE" :
color = "#FFFFFF";
break;

case "BLACK" :
color = "#000000";
break;

case "RED" :
color = "#FF0000";
break;
case "" : // i think problem is here

color = "";
break;
}

return color;
}

-----------

if all color colums are not null, everything okay.. but, i'm getting below the error if any color colums is null..

------error-----

Exception Details: System.InvalidCastException: Specified cast is not valid.

Line 159: <td bgcolor="<%# Team_Colors((string) DataBinder.Eval(Container.DataItem, "color4")) %>"
------------
how can i solve this problem ?

thanks..If it's Null at times, try Switch(color.ToString())
Or add the .ToString to where the color is actually being read from the database.

Hope this helps, but may need to see more code...

Zath
i tried that Switch(color.ToString()) but same eror :(
it's ok, thanks Zath..

<%# Team_Colors(DataBinder.Eval(Container.DataItem, "color1").ToString()) %>
<%# Team_Colors(DataBinder.Eval(Container.DataItem, "color2").ToString()) %>
<%# Team_Colors(DataBinder.Eval(Container.DataItem, "color3").ToString()) %>
<%# Team_Colors(DataBinder.Eval(Container.DataItem, "color4").ToString()) %>
I just tried your function and it works ok for me.
Are there any other colors in the database not accounted for?

Have you tried setting a break point in your code to help debug?

Maybe a little more code might help.

Zath

0 comments:

Post a Comment