Showing posts with label systeminvalidcastexception. Show all posts
Showing posts with label systeminvalidcastexception. Show all posts

Saturday, March 31, 2012

System.InvalidCastException

Hope someone can help. I am trying to get a submit button working and
getting this error now System.InvalidCastException: Object must implement
IConvertible. This is showing up on the ExecuteNonQuery line. Below is the
code that I have in my Page_load. I also have no idea of what code I would
use in the Submit_Click event to get the insert to work. Any help would be
appreciated
OleDbConnection conn = new
OleDbConnection("Provider=OraOLEDB.Oracle.1;Persist Security
Info=False;"+"User ID=conference;Password=conf00;Data
Source=ntdrp001.world;");
OleDbCommand command = new OleDbCommand("CONF-REQUEST_INSERT", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("DropDownList1", OleDbType.VarChar).Value =
DropDownList1;
command.Parameters.Add("DropDownList2", OleDbType.VarChar).Value =
DropDownList2;
command.Parameters.Add("txtEStartDate", OleDbType.Date).Value =
txtEStartDate;
command.Parameters.Add("txtEEndDate", OleDbType.Date).Value = txtEEndDate;
command.Parameters.Add("txtEStartTime", OleDbType.Numeric).Value =
txtEStartTime;
command.Parameters.Add("txtEEndTime", OleDbType.Numeric).Value =
txtEEndTime;
command.Parameters.Add("txtEventName", OleDbType.VarChar).Value =
txtEventName;
command.Parameters.Add("txtEventSize", OleDbType.Numeric).Value =
txtEventSize;
command.Parameters.Add("txtSStartDate", OleDbType.Date).Value =
txtSStartDate;
command.Parameters.Add("txtSStartTime", OleDbType.Numeric).Value =
txtSStartTime;
command.Parameters.Add("txtEventDescription", OleDbType.VarChar).Value =
txtEventDescription;
command.Parameters.Add("txtSpecialRequirements", OleDbType.VarChar).Value =
txtSpecialRequirements;
conn.Open();
int rows = command.ExecuteNonQuery();
conn.Close();Hi, Brian,
The reason is that you directly use the web control objects for the value as
signments. You have to use their properties. like:
command.Parameters.Add("DropDownList1", OleDbType.VarChar).Value = DropDownL
ist1.SelectedItem.Value;
command.Parameters.Add("txtEStartDate", OleDbType.Date).Value = txtEStartDat
e.Text;
Bin Song, MCP

System.InvalidCastException

I have UI Page.aspx which has this class:
PAGE.ASPX
private class Blah
public bVar as boolean
end class
On page load this class is added to the collection ColBlah and sent to the
function in business layer which has identical class defined.
BusLayer.vb
private class Blah
bVar as boolean
end class
class BusLayer
Public function Process(oCol as collection)
dim oObject, oBlah as Blah
for each oObject in oCol
oBlah=CType(oObject,Blah)
next oCol
end class
the line oBlah=CType(oObject,Blah) generates the following exception
System.InvalidCastException
Why? Anybody?A class can't exist in two places at the same time. Just because they have
the same name and share all the same members, doesn't make them the same.
As far as .NET is concerned, you might as well be trying to cast a textbox
to a database connection.
This class should be defined in your business layer ONLY...and your aspx
page should create an instance of THAT class.
Karl
http://www.openmymind.net/
http://www.codebetter.com/
"Mike Kansky" <MikeKansky@.discussions.microsoft.com> wrote in message
news:8DD38BB8-E1A6-4C92-8629-918A5F3FAC83@.microsoft.com...
>I have UI Page.aspx which has this class:
> PAGE.ASPX
> private class Blah
> public bVar as boolean
> end class
>
> On page load this class is added to the collection ColBlah and sent to the
> function in business layer which has identical class defined.
> BusLayer.vb
> private class Blah
> bVar as boolean
> end class
> class BusLayer
> Public function Process(oCol as collection)
> dim oObject, oBlah as Blah
> for each oObject in oCol
> oBlah=CType(oObject,Blah)
> next oCol
> end class
> the line oBlah=CType(oObject,Blah) generates the following exception
> System.InvalidCastException
> Why? Anybody?
>

System.InvalidCastException:

I have a page that gets a value from the querystring. I believe people click certain javascript functions on the page that sometimes appends a "#". I have never seen a page error out to this, but I am getting my logfile full of errors like the one below?

System.InvalidCastException: Cast from string "146586#" to type 'Integer' is not valid.

What would be a good way to stop this? Should I somehow trim the very last character if its equal to a "#" .

If so, how can I achieve this?

Thanks
mike123That is weird. The only time I have seen a # appended is when somebody uses the onclick in a A tag

for instance:Click me

In my opinion and to avoid these @.$R # signs is to use this:

Click Me

System.InvalidCastException:

I get a System.InvalidCastException on the following code.

ObjtInterestLadder.dblPrinCcyAmt = (double) dsRecs.Tables["DetailData"].Rows[iSub]["Prin_Ccy_Amt"];

Why is this.

When I retrieve the data to a string it is OK

sData = (string) dsRecs.Tables["DetailData"].Rows[iSub]["Prin_Ccy_Amt"].ToString();

have you checked for NULL values?


franklb wrote:

Why is this.

When I retrieve the data to a string it is OK

sData = (string) dsRecs.Tables["DetailData"].Rows[iSub]["Prin_Ccy_Amt"].ToString();


What is it showing when you do that ? If it is null or blank it will show exception.

System.InvalidCastException: Error de QueryInterface para la interfaz GrosConexion._ClaFun

Hi,
I'km newbie in asp.net. My problem is the subject of this post 'System.InvalidCastException: Error de QueryInterface para la interfaz GrosConexion._ClaFunciones'
I have a dll from a software provider, and i must use your functions from an asp page. My code is (in Page_Load Event of a webform)

Dim RPSGrosVariablesAs GrosVariablesGenererales.ClaVariables

RPSGrosVariables =New GrosVariablesGenererales.ClaVariables

Dim RPSGrosConexionAs GrosConexion.ClaFunciones

RPSGrosConexion =New GrosConexion.ClaFunciones

IfNot IsPostBackThen

gblRutaINI = System.Web.HttpRuntime.AppDomainAppPath & "Prueba.INI"

TextBox1.Text = gblRutaINI

If RPSGrosConexion.AbrirConexion(gblRutaINI, gblMensajeRPS) < 0Then

'Connection fails

Else

'Connection to database ok

EndIf

EndIf


The function AbrirConexion connects to a SQL Server database and returns a short.
If short is less than 0 the connection is OK
I have read very posts in a lot of forums, but my problem is not resolved.
Anyone cab help me? Sorry from my English
Many, many thanx

Guessing of course - without knowing what's in the functions etc.., but try changing this line
If RPSGrosConexion.AbrirConexion(gblRutaINI, gblMensajeRPS) < 0Then
to
If RPSGrosConexion.AbrirConexion(textbox1.text, gblMensajeRPS) < 0Then
Also , I would use a try block - something like...
Try
Dim MyShort as Short
MyShort =RPSGrosConexion.AbrirConexion(textbox1.text, gblMensajeRPS)
'do other stuff here with open connection - I'm guessing
Catch exc as exception
Finally
'close connection- if the AbrirConexion leaves it open- I don't know
End Try
HTH


Today, when I turn on my computer, the first time I try the code (without your modification), it runs ok. But the next times i have the same error.
The function AbrirConexion open the connection but don't close it.
And I don't know how to close a connection open by a function.
I don't understand it
Help me, please
Well , we can't guess at it...
check out the Reflector tool here ...http://www.aisto.com/roeder/dotnet/
this will aloow you to "see" inside the DLL - it's methods etc..
use that to read through what functions / methods are available. Youwill run the program and tell it to open the DLL for the component yourare trying to use.
Also, can you get support from the authors of this DLL ?
Hope That Helps

OK, I'll try it
Many thanx

System.InvalidCastException: Specified cast is not valid

I keep geting the exception:

System.InvalidCastException: Specified cast is not valid.

I get this when I try to pass a DataRow into an object method. The line that
causes this error is:

policy.SetValues(dr);

Here is part of the class that contains the method that I want to call:

using System;
using System.Data;
using System.Collections;

namespace IDUL.Policies
{

/// <summary>
/// </summary>
public class Policy
{
private int _qid;
private int _cid;
private string _policy_number;
private string _inception_date;
private string _expiry_date;
private float _raw_premium;
private float _policy_fee;
private float _admin_fee;
private float _ipt;
private float _total_premium;
private bool _is_renewal;
private string _operator;
private string _date_quoted;
private bool _on_cover;
private string _on_cover_date;
private string _on_cover_operator;

/// <summary>
/// </summary>
public Policy()
{
Trace.Constructor("Policy()");
}

/// <summary>
/// </summary>
public Policy(DataRow dr)
{
Trace.EnterConst("Policy(dr)");

if (dr != null)
{
SetValues(dr);
}

Trace.LeaveConst("Policy(dr)");
}

public void SetValues(DataRow dr)
{
_qid = (int)dr["qid"];
_cid = (int)dr["cid"];
_policy_number = dr["policy_number"].ToString();
_inception_date = dr["inception_date"].ToString();
_expiry_date = dr["expiry_date"].ToString();
_raw_premium = (float)dr["raw_premium"];
_policy_fee = (float)dr["policy_fee"];
_admin_fee = (float)dr["admin_fee"];
_ipt = (float)dr["ipt"];
_total_premium = (float)dr["total_premium"];
_is_renewal = (bool)dr["is_renewal"];
_operator = dr["operator"].ToString();
_date_quoted = dr["date_quoted"].ToString();
_on_cover = (bool)dr["on_cover"];
_on_cover_date = dr["on_cover_date"].ToString();
_on_cover_operator = dr["on_cover_operator"].ToString();
}
}

The code that instantiates the class and calls the method is in here:

foreach (DataTable dt in dsPolicies.Tables)
{
foreach (DataRow dr in dt.Rows)
{
Policy policy = new Policy();

policy.SetValues(dr);

arrPolicies.Add(policy);
}
}

Any ideas what is causing this exception?Floela <floela@.benjamin.com> wrote:
> I keep geting the exception:
> System.InvalidCastException: Specified cast is not valid.
>
> I get this when I try to pass a DataRow into an object method. The line that
> causes this error is:
> policy.SetValues(dr);

I'm sure that's one part of the stack, but I don't think that's going
to be the actual direct causal line. I suspect it's somewhere within
SetValues itself. Have you tried stepping through SetValues to see
where the exception is thrown?

--
Jon Skeet - <skeet@.pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

> I get this when I try to pass a DataRow into an object method. The line
that
> causes this error is:
> policy.SetValues(dr);
Inside SetValues there are many cast without checking,
i wonder if they are all safe ?

> public void SetValues(DataRow dr)
> {
> _qid = (int)dr["qid"];
> _cid = (int)dr["cid"];
> _raw_premium = (float)dr["raw_premium"];
> _policy_fee = (float)dr["policy_fee"];
> _admin_fee = (float)dr["admin_fee"];
> _ipt = (float)dr["ipt"];
> _total_premium = (float)dr["total_premium"];
> _is_renewal = (bool)dr["is_renewal"];
> _on_cover = (bool)dr["on_cover"];
> }
Floela <floela@.benjamin.com> wrote:
> > I'm sure that's one part of the stack, but I don't think that's going
> > to be the actual direct causal line. I suspect it's somewhere within
> > SetValues itself.
> SetValues is pretty simple - just assigning the values from the DataRow to
> private variables within the class (see my original post). There's nothing
> glaring as to where the problem could be within this method.

Yes there is - you've got lots of casts in SetValues. I'm sure it'll be
one of those which is failing.

> > Have you tried stepping through SetValues to see
> > where the exception is thrown?
> No I haven't, as I'm actually coding the application using TextPad, not
> VS.NET.

Ah. That's a pain. Can you print out a stack trace to show exactly
where it's failing?

--
Jon Skeet - <skeet@.pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

System.InvalidCastException: Specified cast is not

The system worked well until the personnel of the support installed Crystal
Reports Framework 2.0 starting from this moment started to give the mistake below.
Does anybody know how to explain to me the why is happening this mistake?

Server Error in '/SISTEMA' Application.
Specified cast is not valid.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.

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

Source Error:
Line 240: //{Line 241: ceReportObject = objReports[1];

Line 242: ceReport = (Report)ceReportObject;

Line 243: ceParameters = ceReport.ReportParameters;Line 244:

Source File:
d:\projetos\sistema\wwwroot\formrelatoriosreservasspever1.aspx.cs
Line: 242

Stack Trace:
[InvalidCastException: Specified cast is not valid.]
sistema.FormRelatoriosReservasSPEVer1.PassarParametros(String
strParam, String strTipoParam, String strNomeParam) in
d:\projetos\sistema\wwwroot\formrelatoriosreservasspever1.aspx.cs:242
sistema.FormRelatoriosReservasSPEVer1.VerRelatorio() in
d:\projetos\sistema\wwwroot\formrelatoriosreservasspever1.aspx.cs:503
sistema.FormRelatoriosReservasSPEVer1.InicializaCrystal() in
d:\projetos\sistema\wwwroot\formrelatoriosreservasspever1.aspx.cs:583
sistema.FormRelatoriosReservasSPEVer1.InitializeComponent() in
d:\projetos\sistema\wwwroot\formrelatoriosreservasspever1.aspx.cs:628
sistema.FormRelatoriosReservasSPEVer1.OnInit(EventArgs e) in
d:\projetos\sistema\wwwroot\formrelatoriosreservasspever1.aspx.cs:619
System.Web.UI.Control.InitRecursive(Control namingContainer)
System.Web.UI.Page.ProcessRequestMain()

Version Information: Microsoft .NET Framework Version:1.1.4322.2032;
ASP.NET Version:1.1.4322.2032

Description
Crystal Enterprise 10, Crystal Reports 10 e VS.Net 2003

Thanks

Set a break point on that line and debug. What type of object is objReports[1], as displayed in the Watch window? and what type of object is ceReportObject, which you are trying to assign it to?

System.InvalidCastException: Specified cast is not valid.

Hello All,
Please help. I get the following error from my webpage:
System.InvalidCastException: Specified cast is not valid.
at Time.MaintAtRiskProjects.UpdateProject(String Project, String
AtRiskCode, String Comment)
Code for UpdateProject(String Project, String AtRiskCode, String Comment)
is:
Private Sub UpdateProject(ByVal Project As String, ByVal AtRiskCode As
String, ByVal Comment As String)
Try
Dim strProject As String = Trim(Project)
Dim strAtRiskCode As String = Trim(AtRiskCode)
Dim strComment As String = Trim(Comment)
Dim r As AtRiskProjectsDS.AtRiskProjectsRow
Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow =
AtRiskProjDS.AtRiskProjects.Select(AtRiskProjDS.AtRiskProjects.ProjectColumn
.ColumnName
& "= '" & strProject & "' AND " &
AtRiskProjDS.AtRiskProjects.AtRiskCodeColumn.ColumnName & "= '" &
strAtRiskCode & "' ")
If rows.Length <> 0 Then
r = rows(0)
If r.Comment <> strComment Then
r.Comment = strComment
End If
End If
Catch ex As Exception
Trace.Write(ex.ToString)
End Try
End Sub
UpdateProject(ByVal Project As String, ByVal AtRiskCode As String, ByVal
Comment As String) is being called from an update button I have in the page.
The code for Update click is as follows:
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnUpdate.Click
Try
Dim strProject As String = Trim(lblProject.Text)
AtRiskProjDS.Clear()
AtRiskProjDS = LoadAtRiskProjDS(strProject)
For Each item As DataGridItem In dgAtRiskInfo.Items
If item.ItemType = ListItemType.Item Or item.ItemType =
ListItemType.AlternatingItem Then
Dim RiskCodeOld As CheckBox = CType(item.FindControl("chkCodeOld"),
CheckBox)
Dim RiskCodeNew As CheckBox = CType(item.FindControl("chkCodeNew"),
CheckBox)
Dim AtRiskCode As TextBox = CType(item.FindControl("txtAtRiskCode"),
TextBox)
Dim Description As Label = CType(item.FindControl("lblDescription"), Label)
Dim Comment As TextBox = CType(item.FindControl("txtComment"), TextBox)
Dim strAtRiskCode As String = Trim(AtRiskCode.Text)
Dim strDescription As String = Trim(Description.Text)
Dim strComment As String = Trim(Comment.Text)
If RiskCodeOld.Checked = False And RiskCodeNew.Checked = True Then
InsertProject(RiskCodeNew.Checked, strProject, strAtRiskCode,
strDescription, strComment)
RiskCodeOld.Checked = RiskCodeNew.Checked
ElseIf RiskCodeOld.Checked = True And RiskCodeNew.Checked = False Then
DeleteProject(strProject, strAtRiskCode)
RiskCodeOld.Checked = RiskCodeNew.Checked
Else
UpdateProject(strProject, strAtRiskCode, strComment)
End If
End If
Next
SubmitChanges(strProject)
Catch ex As Exception
Trace.Write(ex.ToString)
End Try
End Sub
Here is what the code for ASPX page looks like:
<%@dotnet.itags.org. Import namespace="Time" %>
<%@dotnet.itags.org. Import namespace="System.Data" %>
<%@dotnet.itags.org. Register TagPrefix="uc1" TagName="footer" src="http://pics.10026.com/?src=../footer.ascx" %>
<%@dotnet.itags.org. Register TagPrefix="uc1" TagName="header" src="http://pics.10026.com/?src=../header.ascx" %>
<%@dotnet.itags.org. Page Language="vb" AutoEventWireup="false"
Codebehind="MaintAtRiskProjects.aspx.vb"
Inherits="Time.MaintAtRiskProjects"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>MaintAtRiskProjects</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
<LINK href="http://links.10026.com/?link=../master.css" type="text/css" rel="stylesheet">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="MaintAtRiskProjectsFrm" method="post" runat="server">
<uc1:header id="PageHeader" runat="server"></uc1:header>
<P><asp:dropdownlist id="ddlProject" style="Z-INDEX: 101; LEFT: 16px;
POSITION: absolute; TOP: 72px"
runat="server" OnSelectedIndexChanged="DisplayAtRiskProjInfo"
Font-Names="Lucida Console, Courier New"
Width="168px" autopostback="True"></asp:dropdownlist></P>
<hr style="Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 104px">
<asp:Button id="btnReport" style="Z-INDEX: 106; LEFT: 504px; POSITION:
absolute; TOP: 64px"
runat="server" Width="97px" Text="View Report"></asp:Button>
<asp:Button id="btnUpdate" style="Z-INDEX: 105; LEFT: 280px; POSITION:
absolute; TOP: 64px"
runat="server" Width="72px" Height="24px"
Text="Update"></asp:Button><asp:label id="lblProject" style="Z-INDEX: 104;
LEFT: 8px; POSITION: absolute; TOP: 128px"
runat="server" Width="160px" ForeColor="#CC0000"
Height="24px"></asp:label><asp:datagrid id="dgAtRiskInfo" style="Z-INDEX:
103; LEFT: 184px; POSITION: absolute; TOP: 128px"
runat="server" Width="385px" Height="160px" ShowFooter="False"
AutoGenerateColumns="False">
<AlternatingItemStyle BackColor="MistyRose"></AlternatingItemStyle>
<ItemStyle HorizontalAlign="Right"></ItemStyle>
<HeaderStyle ForeColor="#CC0000" BackColor="Silver"></HeaderStyle>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:TextBox ID="txtAtRiskCode" Text='<%
#Container.DataItem("AtRiskCode") %>' Runat=server Visible=False>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="chkCodeOld" Checked='<%
#Container.DataItem("RiskCodeFlag") %>' Runat="server" Visible=False>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Check/Uncheck">
<ItemTemplate>
<asp:CheckBox ID="chkCodeNew" Checked='<%
#Container.DataItem("RiskCodeFlag") %>' Width="15px" Runat=server>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription" text='<%
#Container.DataItem("Description") %>' width="250px" runat=server>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Comment">
<ItemTemplate>
<asp:TextBox ID="txtComment" Text='<% #Container.DataItem("Comment")
%>' Width="400px" Runat=server>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid></form>
</body>
</HTML>
Please help.. Can't figure out what is going on.
Thanks,
Biva
----
--
----
--"Biva" <biva.yauchler@.redprairie.com> wrote in message
news:41dac14e$0$82454$39cecf19@.news.twtelecom.net...
> Hello All,
> Please help. I get the following error from my webpage:
> System.InvalidCastException: Specified cast is not valid.
> at Time.MaintAtRiskProjects.UpdateProject(String Project, String
> AtRiskCode, String Comment)
> Code for UpdateProject(String Project, String AtRiskCode, String Comment)
> is:
...

> Please help.. Can't figure out what is going on.
>
I can't figure out what's going on either, since you did not tell us which
line was causing the error.
This sort of thing happens frequently when a database column contains NULL.
NULL is not a value, so if you try to treat it as a string, you'll get the
invalid cast exception.
John Saunders

John,
My frustration is that it works on my PC that has Framework 1.1.
But when I move it to production that has framework 1.0, it does not
work.
I have the backward compatibility turned on, so it should work.
Since it is on production, i don't have an easy way to debug.
All I could do was set debug=true on web.config and look at the
trace.axd to get that error.
Is there an easy way for me to find out what line is actually giving me
that error?
thanks...
*** Sent via Developersdex http://www.examnotes.net ***
Don't just participate in USENET...get rewarded for it!
"sqlgirl" <sqlgirl@.devdex.com> wrote in message
news:ur12b9n8EHA.1396@.tk2msftngp13.phx.gbl...
>
> John,
> My frustration is that it works on my PC that has Framework 1.1.
> But when I move it to production that has framework 1.0, it does not
> work.
> I have the backward compatibility turned on, so it should work.
> Since it is on production, i don't have an easy way to debug.
> All I could do was set debug=true on web.config and look at the
> trace.axd to get that error.
> Is there an easy way for me to find out what line is actually giving me
> that error?
I don't know, but this kind of thing is a reason to develop on the platform
you're going to use in production.
John Saunders
Here is my DeleteProject method.
Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow =
AtRiskProjDS.AtRiskProjects.Select(AtRiskProjDS.AtRiskProjects.ProjectCo
lumn.ColumnName & "= '" & strProject & "' AND " &
AtRiskProjDS.AtRiskProjects.AtRiskCodeColumn.ColumnName & "= '" &
strAtRiskCode & "' ")
is the statement that is not being liked for some reason.
Sub DeleteProject(ByVal Project As String, ByVal AtRiskCode As String)
Try
Dim strProject As String = Project
Dim strAtRiskCode As String = AtRiskCode
Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow =
AtRiskProjDS.AtRiskProjects.Select(AtRiskProjDS.AtRiskProjects.ProjectCo
lumn.ColumnName & "= '" & strProject & "' AND " &
AtRiskProjDS.AtRiskProjects.AtRiskCodeColumn.ColumnName & "= '" &
strAtRiskCode & "' ")
Trace.Write("proj1: " & strProject & ", code1: " &
strAtRiskCode)
Dim r As AtRiskProjectsDS.AtRiskProjectsRow
If rows.Length <> 0 Then
r = rows(0)
r.Delete()
End If
Catch ex As Exception
Trace.Write(ex.ToString)
End Try
End Sub
*** Sent via Developersdex http://www.examnotes.net ***
Don't just participate in USENET...get rewarded for it!
"sqlgirl" <sqlgirl@.devdex.com> wrote in message
news:OuhDdyo8EHA.3592@.TK2MSFTNGP09.phx.gbl...
> Here is my DeleteProject method.
> Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow =
> AtRiskProjDS.AtRiskProjects.Select(AtRiskProjDS.AtRiskProjects.ProjectCo
> lumn.ColumnName & "= '" & strProject & "' AND " &
> AtRiskProjDS.AtRiskProjects.AtRiskCodeColumn.ColumnName & "= '" &
> strAtRiskCode & "' ")
Ok, if there's something on that line that ASP.NET doesn't like, then
simplify it:
Dim projectColumnName as String =
AtRiskProjDS.AtRiskProjects.ProjectColumn.ColumnName
Dim atRiskCodeColumnName As String =
AtRiskProjDS.AtRiskProjects.AtRiskCodeColumn.ColumnName
Dim query As String = projectColumnName & "= '" & strProject & "' AND " &
atRiskCodeColumnName & "= '" & strAtRiskCode & "' "
Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow =
AtRiskProjDS.AtRiskProjects.Select(query)
Try that and tell us which line has the problem.
John Saunders
I had defined rows() variable as my dataset.datatablerowtype.
eg.
Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow
Framework 1.0 did not like it.
After I changed the rows() variable to simple datarow type as shown
below, it worked fine.
Dim rows() As datarow
Just so if anyone has this problem in the future.
*** Sent via Developersdex http://www.examnotes.net ***
Don't just participate in USENET...get rewarded for it!

System.InvalidCastException: Specified cast is not valid.

Hi
I get the this error when i run my code:
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
this.DataGrid1.DataSource= this.DataSource();
this.DataGrid1.DataBind();
}
private ICollection DataSource()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("kol0",typeof(Int16)));
for (int i=0;i<10;i++)
{
DataRow dr = dt.NewRow();
if (i%2==0)
{
dr[0]=1;
}
else
{
dr[0]=0;
}
dt.Rows.Add(dr);
}
DataView dv;
dv = new DataView(dt);
return dv;
}
private void DataGrid1_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
int i = e.Item.ItemIndex;
if(i==0)
{
((DropDownList)e.Item.Cells[0].Controls[0]).SelectedValue="one";
}
}
page:
one two
one two
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 96px; POSITION:
absolute; TOP: 56px" runat="server"
Height="216px" Width="448px" AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:DropDownList ID="dll" Runat="server">
<asp:ListItem Value="0">one</asp:ListItem>
<asp:ListItem Value="1">two</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
ch JIt would help if you told us the line #. Is it at:
((DropDownList)e.Item.Cells[0].Controls[0]).SelectedValue="one";
First of all, it looks like you are doing that when ItemIndex == 0
wouldn't that be ur HeaderTemplate in which case cell[0].Controls[0]. really
might not be what you expect. Secondly, you might prefer
e.Item.FindControl("dll") or e.Item.Cells[0].FindContorl("dll") (not sure
which will work, favor the first one if it'll work) over using indexes. It
makes your code more flexible and less likely to break. Sometimes literals
(like spaces and newlines) are converted to controls, so while you might
think it's Controls[0], it might really be Controls[1] 'cuz there was a
newline before it.
It should be pretty easy to step through your code and debug though...
Karl
MY ASP.Net tutorials
http://www.openmymind.net/
http://openmymind.net/redirector.aspx?documentId=51 - Learn about AJAX!
"Jimmy" <beffer@.gmail.com> wrote in message
news:eX0b2r$yFHA.2556@.TK2MSFTNGP10.phx.gbl...
> Hi
> I get the this error when i run my code:
>
> private void Page_Load(object sender, System.EventArgs e)
> {
> // Put user code to initialize the page here
> this.DataGrid1.DataSource= this.DataSource();
> this.DataGrid1.DataBind();
> }
> private ICollection DataSource()
> {
> DataTable dt = new DataTable();
>
> dt.Columns.Add(new DataColumn("kol0",typeof(Int16)));
>
> for (int i=0;i<10;i++)
> {
> DataRow dr = dt.NewRow();
> if (i%2==0)
> {
> dr[0]=1;
>
> }
> else
> {
> dr[0]=0;
>
> }
> dt.Rows.Add(dr);
> }
> DataView dv;
> dv = new DataView(dt);
> return dv;
> }
> private void DataGrid1_ItemDataBound(object sender,
> System.Web.UI.WebControls.DataGridItemEventArgs e)
> {
> int i = e.Item.ItemIndex;
> if(i==0)
> {
> ((DropDownList)e.Item.Cells[0].Controls[0]).SelectedValue="one";
> }
>
> }
>
> page:
>
> one two
> one two
> <asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 96px; POSITION:
> absolute; TOP: 56px" runat="server"
> Height="216px" Width="448px" AutoGenerateColumns="False">
> <Columns>
> <asp:TemplateColumn>
> <ItemTemplate>
> <asp:DropDownList ID="dll" Runat="server">
> <asp:ListItem Value="0">one</asp:ListItem>
> <asp:ListItem Value="1">two</asp:ListItem>
> </asp:DropDownList>
> </ItemTemplate>
> </asp:TemplateColumn>
> </Columns>
> </asp:DataGrid>
> ch J
>
>
>

System.InvalidCastException: Specified cast is not valid.

Hi

I get the this error when i run my code:

private void Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

this.DataGrid1.DataSource= this.DataSource();

this.DataGrid1.DataBind();

}

private ICollection DataSource()

{

DataTable dt = new DataTable();

dt.Columns.Add(new DataColumn("kol0",typeof(Int16)));

for (int i=0;i<10;i++)

{

DataRow dr = dt.NewRow();

if (i%2==0)

{

dr[0]=1;

}

else

{

dr[0]=0;

}

dt.Rows.Add(dr);

}

DataView dv;

dv = new DataView(dt);

return dv;

}

private void DataGrid1_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)

{

int i = e.Item.ItemIndex;

if(i==0)

{

((DropDownList)e.Item.Cells[0].Controls[0]).SelectedValue="one";

}

}

page:

one two
one two
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 96px; POSITION:
absolute; TOP: 56px" runat="server"
Height="216px" Width="448px" AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:DropDownList ID="dll" Runat="server">
<asp:ListItem Value="0">one</asp:ListItem>
<asp:ListItem Value="1">two</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid
ch JIt would help if you told us the line #. Is it at:
((DropDownList)e.Item.Cells[0].Controls[0]).SelectedValue="one";

First of all, it looks like you are doing that when ItemIndex == 0
wouldn't that be ur HeaderTemplate in which case cell[0].Controls[0]. really
might not be what you expect. Secondly, you might prefer
e.Item.FindControl("dll") or e.Item.Cells[0].FindContorl("dll") (not sure
which will work, favor the first one if it'll work) over using indexes. It
makes your code more flexible and less likely to break. Sometimes literals
(like spaces and newlines) are converted to controls, so while you might
think it's Controls[0], it might really be Controls[1] 'cuz there was a
newline before it.

It should be pretty easy to step through your code and debug though...

Karl

--
MY ASP.Net tutorials
http://www.openmymind.net/
http://openmymind.net/redirector.aspx?documentId=51 - Learn about AJAX!

"Jimmy" <beffer@.gmail.com> wrote in message
news:eX0b2r$yFHA.2556@.TK2MSFTNGP10.phx.gbl...
> Hi
> I get the this error when i run my code:
>
> private void Page_Load(object sender, System.EventArgs e)
> {
> // Put user code to initialize the page here
> this.DataGrid1.DataSource= this.DataSource();
> this.DataGrid1.DataBind();
> }
> private ICollection DataSource()
> {
> DataTable dt = new DataTable();
>
> dt.Columns.Add(new DataColumn("kol0",typeof(Int16)));
>
> for (int i=0;i<10;i++)
> {
> DataRow dr = dt.NewRow();
> if (i%2==0)
> {
> dr[0]=1;
>
> }
> else
> {
> dr[0]=0;
>
> }
> dt.Rows.Add(dr);
> }
> DataView dv;
> dv = new DataView(dt);
> return dv;
> }
> private void DataGrid1_ItemDataBound(object sender,
> System.Web.UI.WebControls.DataGridItemEventArgs e)
> {
> int i = e.Item.ItemIndex;
> if(i==0)
> {
> ((DropDownList)e.Item.Cells[0].Controls[0]).SelectedValue="one";
> }
>
> }
>
> page:
>
> one two
> one two
> <asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 96px; POSITION:
> absolute; TOP: 56px" runat="server"
> Height="216px" Width="448px" AutoGenerateColumns="False">
> <Columns>
> <asp:TemplateColumn>
> <ItemTemplate>
> <asp:DropDownList ID="dll" Runat="server">
> <asp:ListItem Value="0">one</asp:ListItem>
> <asp:ListItem Value="1">two</asp:ListItem>
> </asp:DropDownList>
> </ItemTemplate>
> </asp:TemplateColumn>
> </Columns>
> </asp:DataGrid>
> ch J
>
>

System.InvalidCastException: Specified cast is not valid.

Hello All,
Please help. I get the following error from my webpage:

System.InvalidCastException: Specified cast is not valid.
at Time.MaintAtRiskProjects.UpdateProject(String Project, String
AtRiskCode, String Comment)

Code for UpdateProject(String Project, String AtRiskCode, String Comment)
is:

Private Sub UpdateProject(ByVal Project As String, ByVal AtRiskCode As
String, ByVal Comment As String)

Try

Dim strProject As String = Trim(Project)

Dim strAtRiskCode As String = Trim(AtRiskCode)

Dim strComment As String = Trim(Comment)

Dim r As AtRiskProjectsDS.AtRiskProjectsRow

Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow =
AtRiskProjDS.AtRiskProjects.Select(AtRiskProjDS.At RiskProjects.ProjectColumn.ColumnName
& "= '" & strProject & "' AND " &
AtRiskProjDS.AtRiskProjects.AtRiskCodeColumn.Colum nName & "= '" &
strAtRiskCode & "' ")

If rows.Length <> 0 Then

r = rows(0)

If r.Comment <> strComment Then

r.Comment = strComment

End If

End If

Catch ex As Exception

Trace.Write(ex.ToString)

End Try

End Sub

UpdateProject(ByVal Project As String, ByVal AtRiskCode As String, ByVal
Comment As String) is being called from an update button I have in the page.
The code for Update click is as follows:

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnUpdate.Click

Try

Dim strProject As String = Trim(lblProject.Text)

AtRiskProjDS.Clear()

AtRiskProjDS = LoadAtRiskProjDS(strProject)

For Each item As DataGridItem In dgAtRiskInfo.Items

If item.ItemType = ListItemType.Item Or item.ItemType =
ListItemType.AlternatingItem Then

Dim RiskCodeOld As CheckBox = CType(item.FindControl("chkCodeOld"),
CheckBox)

Dim RiskCodeNew As CheckBox = CType(item.FindControl("chkCodeNew"),
CheckBox)

Dim AtRiskCode As TextBox = CType(item.FindControl("txtAtRiskCode"),
TextBox)

Dim Description As Label = CType(item.FindControl("lblDescription"), Label)

Dim Comment As TextBox = CType(item.FindControl("txtComment"), TextBox)

Dim strAtRiskCode As String = Trim(AtRiskCode.Text)

Dim strDescription As String = Trim(Description.Text)

Dim strComment As String = Trim(Comment.Text)

If RiskCodeOld.Checked = False And RiskCodeNew.Checked = True Then

InsertProject(RiskCodeNew.Checked, strProject, strAtRiskCode,
strDescription, strComment)

RiskCodeOld.Checked = RiskCodeNew.Checked

ElseIf RiskCodeOld.Checked = True And RiskCodeNew.Checked = False Then

DeleteProject(strProject, strAtRiskCode)

RiskCodeOld.Checked = RiskCodeNew.Checked

Else

UpdateProject(strProject, strAtRiskCode, strComment)

End If

End If

Next

SubmitChanges(strProject)

Catch ex As Exception

Trace.Write(ex.ToString)

End Try

End Sub

Here is what the code for ASPX page looks like:

<%@dotnet.itags.org. Import namespace="Time" %>
<%@dotnet.itags.org. Import namespace="System.Data" %>
<%@dotnet.itags.org. Register TagPrefix="uc1" TagName="footer" src="http://pics.10026.com/?src=../footer.ascx" %>
<%@dotnet.itags.org. Register TagPrefix="uc1" TagName="header" src="http://pics.10026.com/?src=../header.ascx" %>
<%@dotnet.itags.org. Page Language="vb" AutoEventWireup="false"
Codebehind="MaintAtRiskProjects.aspx.vb"
Inherits="Time.MaintAtRiskProjects"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>MaintAtRiskProjects</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
<LINK href="http://links.10026.com/?link=../master.css" type="text/css" rel="stylesheet">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="MaintAtRiskProjectsFrm" method="post" runat="server">
<uc1:header id="PageHeader" runat="server"></uc1:header>
<P><asp:dropdownlist id="ddlProject" style="Z-INDEX: 101; LEFT: 16px;
POSITION: absolute; TOP: 72px"
runat="server" OnSelectedIndexChanged="DisplayAtRiskProjInfo"
Font-Names="Lucida Console, Courier New"
Width="168px" autopostback="True"></asp:dropdownlist></P>
<hr style="Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 104px">
<asp:Button id="btnReport" style="Z-INDEX: 106; LEFT: 504px; POSITION:
absolute; TOP: 64px"
runat="server" Width="97px" Text="View Report"></asp:Button>
<asp:Button id="btnUpdate" style="Z-INDEX: 105; LEFT: 280px; POSITION:
absolute; TOP: 64px"
runat="server" Width="72px" Height="24px"
Text="Update"></asp:Button><asp:label id="lblProject" style="Z-INDEX: 104;
LEFT: 8px; POSITION: absolute; TOP: 128px"
runat="server" Width="160px" ForeColor="#CC0000"
Height="24px"></asp:label><asp:datagrid id="dgAtRiskInfo" style="Z-INDEX:
103; LEFT: 184px; POSITION: absolute; TOP: 128px"
runat="server" Width="385px" Height="160px" ShowFooter="False"
AutoGenerateColumns="False">
<AlternatingItemStyle BackColor="MistyRose"></AlternatingItemStyle>
<ItemStyle HorizontalAlign="Right"></ItemStyle>
<HeaderStyle ForeColor="#CC0000" BackColor="Silver"></HeaderStyle>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:TextBox ID="txtAtRiskCode" Text='<%
#Container.DataItem("AtRiskCode") %>' Runat=server Visible=False>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="chkCodeOld" Checked='<%
#Container.DataItem("RiskCodeFlag") %>' Runat="server" Visible=False>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Check/Uncheck">
<ItemTemplate>
<asp:CheckBox ID="chkCodeNew" Checked='<%
#Container.DataItem("RiskCodeFlag") %>' Width="15px" Runat=server>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription" text='<%
#Container.DataItem("Description") %>' width="250px" runat=server>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Comment">
<ItemTemplate>
<asp:TextBox ID="txtComment" Text='<% #Container.DataItem("Comment")
%>' Width="400px" Runat=server>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid></form>
</body>
</HTML
Please help.. Can't figure out what is going on.

Thanks,

Biva

------------------------

------------------------"Biva" <biva.yauchler@.redprairie.com> wrote in message
news:41dac14e$0$82454$39cecf19@.news.twtelecom.net. ..
> Hello All,
> Please help. I get the following error from my webpage:
> System.InvalidCastException: Specified cast is not valid.
> at Time.MaintAtRiskProjects.UpdateProject(String Project, String
> AtRiskCode, String Comment)
> Code for UpdateProject(String Project, String AtRiskCode, String Comment)
> is:

...

> Please help.. Can't figure out what is going on.

I can't figure out what's going on either, since you did not tell us which
line was causing the error.

This sort of thing happens frequently when a database column contains NULL.
NULL is not a value, so if you try to treat it as a string, you'll get the
invalid cast exception.

John Saunders

John,
My frustration is that it works on my PC that has Framework 1.1.
But when I move it to production that has framework 1.0, it does not
work.
I have the backward compatibility turned on, so it should work.
Since it is on production, i don't have an easy way to debug.
All I could do was set debug=true on web.config and look at the
trace.axd to get that error.
Is there an easy way for me to find out what line is actually giving me
that error?

thanks...

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
"sqlgirl" <sqlgirl@.devdex.com> wrote in message
news:ur12b9n8EHA.1396@.tk2msftngp13.phx.gbl...
>
> John,
> My frustration is that it works on my PC that has Framework 1.1.
> But when I move it to production that has framework 1.0, it does not
> work.
> I have the backward compatibility turned on, so it should work.
> Since it is on production, i don't have an easy way to debug.
> All I could do was set debug=true on web.config and look at the
> trace.axd to get that error.
> Is there an easy way for me to find out what line is actually giving me
> that error?

I don't know, but this kind of thing is a reason to develop on the platform
you're going to use in production.

John Saunders
Here is my DeleteProject method.
Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow =
AtRiskProjDS.AtRiskProjects.Select(AtRiskProjDS.At RiskProjects.ProjectCo
lumn.ColumnName & "= '" & strProject & "' AND " &
AtRiskProjDS.AtRiskProjects.AtRiskCodeColumn.Colum nName & "= '" &
strAtRiskCode & "' ")

is the statement that is not being liked for some reason.

Sub DeleteProject(ByVal Project As String, ByVal AtRiskCode As String)

Try
Dim strProject As String = Project
Dim strAtRiskCode As String = AtRiskCode

Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow =
AtRiskProjDS.AtRiskProjects.Select(AtRiskProjDS.At RiskProjects.ProjectCo
lumn.ColumnName & "= '" & strProject & "' AND " &
AtRiskProjDS.AtRiskProjects.AtRiskCodeColumn.Colum nName & "= '" &
strAtRiskCode & "' ")
Trace.Write("proj1: " & strProject & ", code1: " &
strAtRiskCode)
Dim r As AtRiskProjectsDS.AtRiskProjectsRow

If rows.Length <> 0 Then
r = rows(0)
r.Delete()
End If
Catch ex As Exception
Trace.Write(ex.ToString)
End Try
End Sub

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
"sqlgirl" <sqlgirl@.devdex.com> wrote in message
news:OuhDdyo8EHA.3592@.TK2MSFTNGP09.phx.gbl...
> Here is my DeleteProject method.
> Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow =
> AtRiskProjDS.AtRiskProjects.Select(AtRiskProjDS.At RiskProjects.ProjectCo
> lumn.ColumnName & "= '" & strProject & "' AND " &
> AtRiskProjDS.AtRiskProjects.AtRiskCodeColumn.Colum nName & "= '" &
> strAtRiskCode & "' ")

Ok, if there's something on that line that ASP.NET doesn't like, then
simplify it:

Dim projectColumnName as String =
AtRiskProjDS.AtRiskProjects.ProjectColumn.ColumnNa me
Dim atRiskCodeColumnName As String =
AtRiskProjDS.AtRiskProjects.AtRiskCodeColumn.Colum nName
Dim query As String = projectColumnName & "= '" & strProject & "' AND " &
atRiskCodeColumnName & "= '" & strAtRiskCode & "' "
Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow =
AtRiskProjDS.AtRiskProjects.Select(query)

Try that and tell us which line has the problem.

John Saunders
I had defined rows() variable as my dataset.datatablerowtype.
eg.
Dim rows() As AtRiskProjectsDS.AtRiskProjectsRow

Framework 1.0 did not like it.

After I changed the rows() variable to simple datarow type as shown
below, it worked fine.

Dim rows() As datarow

Just so if anyone has this problem in the future.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Wednesday, March 28, 2012

System.InvalidCastException: Specified cast is not valid.

Hello,

Does somebody haves a solution for this?

Thanks!

Line 74: if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==
ListItemType.AlternatingItem) {
Line 75:
Line 76: DataRowView drv = (DataRowView) e.Item.DataItem;
Line 77:

Source File: links.ascx.cs Line: 76

[InvalidCastException: Specified cast is not valid.]
PortalICT.Links.myDataList_ItemDataBound(Object sender,
DataListItemEventArgs e) in links.ascx.cs:76
System.Web.UI.WebControls.DataList.OnItemDataBound (DataListItemEventArgs
e) +110
System.Web.UI.WebControls.DataList.CreateItem(Int3 2 itemIndex,
ListItemType itemType, Boolean dataBind, Object dataItem) +139
System.Web.UI.WebControls.DataList.CreateControlHi erarchy(Boolean
useDataSource) +686
System.Web.UI.WebControls.BaseDataList.OnDataBindi ng(EventArgs e) +48
System.Web.UI.WebControls.BaseDataList.DataBind() +23
PortalICT.Links.Page_Load(Object sender, EventArgs e) in links.ascx.cs:39
System.Web.UI.Control.OnLoad(EventArgs e) +67
System.Web.UI.Control.LoadRecursive() +29
System.Web.UI.Control.LoadRecursive() +92
System.Web.UI.Control.LoadRecursive() +92
System.Web.UI.Control.LoadRecursive() +92
System.Web.UI.Page.ProcessRequestMain() +713"Arjen" <boah123@.hotmail.com> wrote
> Does somebody haves a solution for this?
> Line 74: if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==
> ListItemType.AlternatingItem) {
> Line 75:
> Line 76: DataRowView drv = (DataRowView) e.Item.DataItem;
> Line 77:
> [InvalidCastException: Specified cast is not valid.]

Arjen,
If you use a DataSet to fill the DataList, then that is the correct syntax.
However, if you use a SqlDataReader, then you must use cast the
DataItem to a System.Data.Common.DbDataRecord.
e.g.
System.Data.Common.DbDataRecord dbDataRecord =
(System.Data.Common.DbDataRecord) e.Item.DataItem;
String s = dbDataRecord.GetString(0);

--

Thanks,
Carl Prothman
Microsoft ASP.NET MVP
http://www.able-consulting.com

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

System.InvalidCastException: Specified cast is not valid.

I have an table with a field of bit. the fields name is Active.
When trying to add that field to a label it gives me the following.
It all works when not using this field.

Error : System.InvalidCastException: Specified cast is not valid.
get {
Line 2057: try {
Line 2058: return ((bool)(this[this.tableJob_Posts.ActiveColumn]));
Line 2059: }
Line 2060: catch (System.InvalidCastException e) {

My code is as follows.

jpDT = jpTA.GetJob_PostsByJobID(jid);

foreach (DataSet1.Job_PostsRow jprin jpDT)

{

if (jpr.Active !=null)

{

this.ActiveLabel.Text = jpr.Active.ToString();

}

Is this field nullable in the database, and are you using TableAdapters? If so, can't simply check for null. You need to instead call the method IsActiveNull() which will be auto-generated by your row class if the field is nullable. This will then check for DbNull instead of null.