.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
Sharon Maxwell
Post New Web Links

[Odd]Specified cast is not valid exception

Posted By:      Posted Date: September 06, 2010    Points: 0   Category :ASP.Net
 
protected float getUserBalance() { string AccountNo = Session["AccNo"].ToString(); myConnection.Open(); float balance = 0; try { OleDbCommand getBalance = new OleDbCommand("Select Balance from BankTransaction where AccountNo = '" + Session["AccNo"] + "'", myConnection); //OleDbDataReader rdrBalance = getBalance.ExecuteReader(); //while (rdrBalance.Read()) //{ // balance = rdrBalance.GetFloat(0); //} balance = float.Parse(getBalance.ExecuteScalar().ToString()); } catch { balance = 0; } myConnection.Close(); return balance; } ===============These are my codes, and it work fine, balance will has a right value, but if I comment the line "balance = float.Parse(getBalance.ExecuteScalar().ToString());"and decomment the 5 lines above, get rid of try catch, I get the error:"Specified cast is not valid"Here is the some informations when I addwatch rdrBalance-        rdrBalance    {System.Data.OleDb.OleDbDataReader}    System.Data.OleDb.OleDbDataReader+        base    {System.Dat


View Complete Post


More Related Resource Links

SSRS 2008 Export to PDF fails for large data with System.Exception: Parameter is not valid

  
Hi, We are working on Range Bar Chart using SSRS 2008. The report has huge data. It is properly displaying the data, but when we tried to export to pdf it is failing with the following exception. Exporting to excel works fine. Also if the report has small/medium data it is property exporting to PDF. It is failing only in case of huge data (we have custom page size of 28" X 14"). Of course the report has lot of expressions we used to customize the colors/text as per our requirements.   Server Error in '/Reports_SQLDEV2008' Application. Parameter 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.Exception: Parameter is not valid. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace:   [Exception: Parameter is not valid.]   [Exception: An error occurred during rendering of the report.]   [Exception: An error occurred during rendering of the report.]    Microsoft.Reporting.WebForms.ServerReport.ServerUrlRequest(Boolean isAbortable, String url, Stream ou

Databind on Gridview throwing System.InvalidCastException. Specific Cast Not Valid

  
Hello, I am working on a web app where when the user enters data into a text box and presses a filter radio button it should filter the Gridview on the page to the criteria entered.  I have done this before in previous applications with the same code listed below, but for some reason I am now getting the InvalidCastExeption error.  Any help would be appreciated, the source database is SQL and the data field is set to nvarchar and I am using a string to compare as you will see in the code.  I am just unsure why this worked in the past and is not working in this scenario. Thanks, Pete protected void filterLName_CheckedChanged(object sender, EventArgs e) { SHCDataContext existingCustomers = new SHCDataContext(); var filterExistingCustomers = existingCustomers.Customers.Where(c => c.custLastName.Contains(lNameTB.Text.ToString())); displayCustGV.DataSource = null; displayCustGV.DataSourceID = null; displayCustGV.DataSource = filterExistingCustomers; displayCustGV.DataBind(); }   Here is the stack trace....  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.I

Invalid cast exception...

  

I thought I had mastered all this.. I'm testing for dbnull. This exception isn't occuring in my code. It's in some other code. What does this "strong typing exception" mean?

Imports DataSet2TableAdapters
Partial Class admin_fixdb
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim I As Integer
        Dim S1 As String
        Dim S2 As String
        Dim S3 As String
        Dim J As Integer
        Dim k As Integer
        Dim l As Integer
        Dim s4 As String
        Dim s5 As String
        Dim s6 As String

        Dim tbllinkadapter As New tblLinkTableAdapter
        Dim tbllink As DataSet2.tblLinkDataTable
        tbllink = tbllinkadapter.GetData
        For Each tbllinkrow As DataSet2.tblLinkRow In tbllink
            If Not IsDBNull(tbllinkrow.SenderLinkOn.ToString) Then
                I = tbllinkrow.SenderLinkOn.IndexOf(".")
                If tbllinkrow.SenderLinkOn.Substring(I - 1, 1) = "_" Then
                    J = Len(tbllinkrow.SenderLinkOn)
                    S1 = tbllinkrow.SenderLinkOn.Substring(0, I - 1)
                    S2 = tbllinkrow.SenderLinkOn.Substring(I, (J - I))
                    S3 = S1 + S2
                    Response.Write("Senderlinkon: " & S3)
  

If / IIf - Cast Exception

  

Hi over there,

I hope this question is not too simple, but I didn't manage to figure out why...
I would need an explanation for following issue:

I'm reading data from a database (MSSQL) and it the column "PersonBirthday" is DBNull.
I wanted to prevent the error (Textbox.Text = DBNull) with an IIF. The thing is I get this
typecast exception:

"Conversion from type 'DBNull' to type 'Date' is not valid."

 This code is NOT working, why?
   txtPersonBirthday.Text = IIf(IsDBNull(.Item("PersonBirthday")) = True, String.Empty, CDate(.Item("PersonBirthday")).ToString("yyyy-MM-dd"))

When I'm using this code, which is for me obviously the same, just with an if-block it works,
and I want to know why - please explain.

           If IsDBNull(.Item("PersonBirthday")) Then
                txtPersonBirthday.Text = String.Empty
            Else
                txtPersonBirthday.Text = CDate(.Item("PersonBirthday")).ToString("yyyy-MM-dd")

Restore error: specified cast is not valid

  
I've got a database from a client (SQL 2008) and when I try and restore the database to my server, I get the following error: specified cast is not valid...

I get the error as I browse for and select the backup file.

Please help!!!

" is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)"

  
I'm attempting to migrate an ASP.NET application from .NET 1.1 to 2.0 (and I'm also moving the development platform from VS.NET 2003 to VS.NET 2005). After some modification the application builds cleanly on the new platform but when I attempt to run in debug mode I see the error shown below. I'm building on a new WinXP-64 machine (AMD Athlon 64 CPU).

If I change the target platform to "x86" in the solution properties, I can't build the app (hundreds of unresolved dependencies).

Can anyone point me in the right direction to solve this problem?

Many thanks

Steve F

Server Error in '/CMISWebAdminDevelopment' Application.

is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)

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.BadImageFormatException: is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)

Source Error:

HTTP Module :Item.Update() gives exception 'Operation is not valid due to the current state of the

  

Hi, I have created a http module to update the list item but when i use the Update function of SPListItem object it gives the error: "Operation is not valid due to the current state of the object". Below is the HTTP Module i have written to update the List Item. Please suggest

 

namespace

 

SiteUsageModule

 

public class SiteUsage : IHttpModule

{

 

Unable to cast COM Object - Exception

  

Hi everyone,

Ive been trying to develop a COM Client application, but without success. My goal is to create an application that can open reports in Cognos Impromptu. Ive got Cognos Impromptu installed on this machine and im using Visual Studio 2008 to develop the client.

I created my project as a consoleapplication in Visual Studio. Next, I added the Impromptu Client Reference via Project > Add Reference > COM. All works fine till now, Visual Studio creates my COM Wrapper dll and adds it to the bin/debug folder.

But when I trry to run my program, it gives me the following Exception:

Unable to cast COM object of type 'ImpromptuClient.ImpromptuApplicationClass' to
 interface type 'ImpromptuClient.IAppAuto'. This operation failed because the Qu
eryInterface call on the COM component for the interface with IID '{2F835754-FB4
F-11CF-8E5F-00401C60350D}' failed due to the following error: No such interface
supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
Press any key to continue . . .

The code I use is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.

Specified cast is not valid

  

Hi,

I have a stored proc. When i execute this proc with correct data from front end i get no error.

However, when i execute the proc with incorrect data i am getting an error

"specified cast s not valid"

I am using SQL server 2008

and below is my proc

USE [AAVouchers_Dev02]
GO
/****** Object:  StoredProcedure [dbo].[USP_UploadData]    Script Date: 10/20/2010 13:28:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[USP_UploadData]
    @FileName varchar (100),
    @CorporateID bigint,
    @CreatedBy bigint,
    --@tbl_FileData tbl_FileData  READONLY
    @data Varchar(max),
    @sendMail Bit =0
 as
SET NOCOUNT ON
 
DECLARE @intError as int,
      @strError as varchar(max),
      @intFILEID int
     
     
SET  @intError = 0
SET @strError = 'No Error'


DEclare @data_xml XML = @data

   

 DECLARE @ErrorTMP TABLE(IntError bigint,StrError Varchar(250))


Begin Try
   
--check Corpor

Linq2SharePoint Invalid Cast Exception

  

I'm trying to use Linq2SharePoint to get a count if items in a document library using the following code:

 

var context = new MyDataContext(webUrl);

var count = (from item in context.MyDocumentLibrary.ScopeToFolder("/", true).OfType<NewBusinessApplication>()
       where item.NewBusinessStatus = "Validation"
       select item).Count()

This should return a count of all NewBusinessApplication documents in all folders with the NewBusinessStatus of Validation.

If a run this on a document library with a mixture of document types it behaves as expected.  However, if a workflow has run on one of the NewBusinessApplication documents I get and InvalidCastException.

It appears from the stack trace that the error is when it's mapping the SPListItem to the concrete type generated by SPMetal but I can't find the specific column that's causing the issue.

Any suggestions or known issues I should look o

Specified cast is not valid during using LINQ

  

I am having problem, Please help me guys .....

these are the errors:

Server Error in '/FYPasp' 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:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidCastException: Specified cast is not valid.]
   System.Data.SqlClient.SqlBuffer.get_Int32() +5002837
   System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i) +38
   Read_DynamicClass1(ObjectMaterializer`1 ) +322
   System.Data.Linq.SqlClient.ObjectReader`2.MoveNext() +32
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +327
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +58


These are the codes:

string metric = Session["ID"].ToString();
            string status = null;
            var onlineStud = db.students.Single(s => s.metricNo.Equals(metric));

          

Sys.WebForms.PageRequestManagerServerErrorException - Specified cast is not valid

  

Hello,

I'm getting the error in the subject whenever I run my application.  I think that it may be related to this:  http://forums.asp.net/p/1038043/1438409.aspx#1438409 and since I have <compilation debug="true" />, I think setting that to false may aid not getting this, as is what it seems as if I read.  So, Is that correct, or is this related to something else?

Thanks.


Specified cast is not valid.

  

I am interfacing a .NET Web Service using gSOAP. All operations in the WS take a "layout" parameter whose type is:

<xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="foo:bar:replaced" id="NDSLayout">
<xs:element msdata:IsDataSet="true" msdata:UseCurrentLocale="true" name="NDSLayout">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Layout">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="FIELD" type="xs:string"/>
<xs:element minOccurs="0" name="INCLUDE" type="xs:boolean"/>
<xs:element minOccurs="0" name="CRITERIA" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>

Windows 2003 64 bit - Web App gives "is not a valid Win32 application. (Exception from HRESULT: 0x80

  

I've got an x86 deployment which is targeted at x86 and works fine on 2003 server 32 bit.

When I install on win 2003 x64, the installer works OK, but I cant get the first web page to display.

I've done a fair bit of googling but not found an answer yet

The error message is:


Server Error in '/MyCompany' Application.
--------------------------------------------------------------------------------

is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)
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.BadImageFormatException: is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 

Stack Trace:


[BadImageFormatException:  is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)]
   System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean thro

gettting exception when uploading a file using IE 6??? not a valid virtual path

  

 

hi,

I have a file upload control and just in IE 6 I get the following error when I try to upload a file. My code is further below.

 

 Exception Details: System.Web.HttpException: '/Members/path//C:\Users\Public\Pictures\Photos\Sample Album\Pensive Parakeet.jpg' is not a valid virtual path

 

MembershipUser newUser =

Membership.GetUser(CreateUserWizard1.UserName);


        HttpFileCollection uploadedFiles = Request.Files;

        for (int i = 0; i < uploadedFiles.Count; i++)
        {

 


            HttpPostedFile file = uploadedFiles[i];
            string fileExt = Path.GetExtension(file.FileName).ToLower();
            string fileName = Path.GetF

TimeOut exception when using MetadataExchangeClient GetMetadata method with valid mex EndpointAddres

  

Hello all,

I have a ServiceHost with a defined tcp mex endpoint at net.tcp://localhost:9003/MyService/mex. Other code can successfully read metadata from the endpoint.

Using the following code, I get a TimeOut exception with this error message even though the timeout interval is set to 3 minutes:

This request operation sent to net.tcp://localhost:9003/CalculatorService/mex did not receive a reply within the configured timeout (00:03:00).  The time allotted to this operation may have been a portion of a longer timeout.  This may be because the service is still processing the operation or because the service was unable to send a reply message.  Please consider increasing the operation timeout (by casting the channel/proxy to IContextChannel and setting the OperationTimeout property) and ensure that the service is able to connect to the client.

MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress);

// mexClient.HttpCredentials = New System.Net.NetworkCredential()

mexClient.ResolveMetadataReferences = true;

mexClient.OperationTimeout = New TimeSpan(0, 3, 0);

MetadataSet metaDocs = mexClient.GetMetadata();

The metadataAddress comes f

DataBase broken. deadline in a few hours, specified cast is not valid. What do i do

  

There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store.

The following message may help in diagnosing the problem: Specified cast is not valid.

 

I'm not sure how it happened but after changing a column in my AccommodationComment table from memberId to username I tested it and all pages which have to do with selecting current user or any user says:

 

System.InvalidCastException was unhandled by user code
  Message=Specified cast is not valid.
  Source=System.Data
  StackTrace:
       at System.Data.SqlClient.SqlBuffer.get_SqlGuid()
       at System.Data.SqlClient.SqlDataReader.GetGuid(Int32 i)
       at System.Web.Security.SqlMembershipProvider.GetUser(String username, Boolean userIsOnline)
       at System.Web.Security.Membership.GetUser(String username, Boolean userIsOnline)
       at System.Web.Security.Membership.GetUser()
       at Actions.getUse

Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend