Specified cast is not valid exception

G

Guest

I am looking for assistance in pinpointing the cause of the following
exception. I am getting a "Specified Cast is not valid" exception on my
page. I am trying to populate a datagrid. One of my columns is a template
column where I'd like to evaluate the data brought back from the db and
populate the column with a "Y" or "N" depending on the value in the db. Here
is the code that is causing it as well as the error (below).


ERROR MESSAGE:
Specified cast is not valid
Exception Details: System.InvalidCastException: Specified cast is not valid.
<%# ((bool)DataBinder.Eval(Container.DataItem, "ReportsTo")) == false ? "N"
: "Y" %>


Code (in aspx page):
<asp:TemplateColumn HeaderText="Reports To" >
<ItemTemplate>
<%# ((bool)DataBinder.Eval(Container.DataItem, "ReportsTo")) == false ?
"N" : "Y" %>
</ItemTemplate>
</asp:TemplateColumn>
 
J

John Saunders

PK9 said:
I am looking for assistance in pinpointing the cause of the following
exception. I am getting a "Specified Cast is not valid" exception on my
page. I am trying to populate a datagrid. One of my columns is a
template
column where I'd like to evaluate the data brought back from the db and
populate the column with a "Y" or "N" depending on the value in the db.
Here
is the code that is causing it as well as the error (below).


ERROR MESSAGE:
Specified cast is not valid
Exception Details: System.InvalidCastException: Specified cast is not
valid.
<%# ((bool)DataBinder.Eval(Container.DataItem, "ReportsTo")) == false ?
"N"
: "Y" %>

What is the type of DataBinder.Eval(Container.DataItem, "ReportsTo")? Try

<%# DataBinder.Eval(Container.DataItem, "ReportsTo").GetType().FullName %>

for debugging purposes.

John Saunders
 
G

Guest

The "ReportsTo" field is an integer. The DataBinder.Eval call returns an
object (unless you pass in a format specifier eg. {0:d}). So I'm now trying
to use the following syntax because an object is returned:
<%# Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "ReportsTo"))) ==
false ? "N" : "Y" %>

This might work if there weren't any dbnull values in the database. So I'm
now trying to figure out how to check for dbnull values in the
OnItemDataCommand event and replace those values with the appropriate text
("N").
 
W

William F. Robertson, Jr.

You are trying to cast an Int32 to a boolean. This is where the invalid
cast is coming from.

Why don't you just put the logic in your sql statment using a case statement
in your select?

Then you don't have to worry about determining Y or N.

bill
 

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

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top