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


Top 5 Contributors of the Month
abhays
Clintonzz
MakarandK
caryfloric
SP
Post New Web Links

Specified cast is not valid

Posted By:      Posted Date: October 20, 2010    Points: 0   Category :Sql Server
 

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


View Complete Post


More Related Resource Links

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

[Odd]Specified cast is not valid exception

  
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

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!!!

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>

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

BinaryFormatter.Deserialize: specified cast is not valid

  

I'm trying to run code like this.

Declare custom data type

    [Serializable]
    public struct Configuration
    {
      public int a;
      public string[] b;
      public string c;
    }

Serialize data to the file

      Configuration config;
      // Assign values to config 
      ...
      // Serialize data
      FileStream fs = new FileStream(configFile, FileMode.Create);
      BinaryFormatter formatter = new BinaryFormatter();
      try
      {
        formatter.Serialize(fs, config);
      }
      catch (SerializationException e)
      {
        ErrorRecord errorRecord = new ErrorRecord(e, "Error writting to the config file.", ErrorCategory.WriteError, config);
        Wr

Using a CompareValidator to check input is a valid date

  
The CompareValidator can do more than just compare two controls. You can also compare it against several of the main .net data types such as Date, Integer, Double and Currency.

To do this you would set Operator="DataTypeCheck" and instead of setting the ControlToCompare or ValueToCompare attributes as you normally would you use the Type="Date" (or any of the data types I have listed above).

How to cast integer values as an array of enum values?

  

Hello all!

I'm working with VS2010 Beta2, ASP.NET and Dynamic Data. I'm using VB but will certainly be happy to receive a C# example if necessary. Laughing

I used a few of Steve's examples (Writing Attributes and Extension Methods for Dynamic Data and Dynamic Data - Hiding Columns in selected PageTemplates) to create a custom property attribute to be applied to a dynamic data column and want it to accept an array of enum values (each value will represent a dynamic data page template where this column should not be displayed).  My new attribute works fine when I hardcode it like this, meaning the HideColumnIn attribute is properly populated with the array of enum values:

<HideColumnIn(PageTemplate.List, PageTemplate.Edit)> _
Public Property My_DD_Column As Object

 

However, I want to store the values to be used for the HideColumnIn in the DB as integer values that correspond to the

ReportViewer :: Failed to enable constraints. But my statement is valid!!

  
  • A
  • n error has occurred during report processing.
      • Exception has been thrown by the target of an invocation.
        • Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

    Why do I keep getting this error, even when not using any data on the report. When I run the query in SQL server I get a resultset. However when I try to render the report I get this error.

    Thanks!


    Path not valid.

      

    hi

    im trying to save a file, filename as current date and time.it will give an error.

    any ideas.

    here is my code

    string datetime=DateTime.Now.ToString();

    if (GridviewtoCSV("~/Admin/doc/Reports/" + batchid.ToString() + datetime + ".csv", transactiongrid) && GridviewtoPDF("~/Admin/doc/Reports/" + batchid.ToString() + datetime + ".pdf", transactiongrid))
                    {


    Unable to cast object of type 'System.Web.Mvc.ValueProviderResult' to type 'System.IConvertible'

      

    Hello,
     Why am I getting this error on line:

                   sp.Price = Convert.ToDecimal(collection.GetValue("Price"));

    sp is :
      SPecials_Templates sp = new SPecials_Templates();

    SPecials_Templates Defined:

        [MetadataType(typeof(SPecials_TemplatesMetaData))]
        public partial class SPecials_Templates
        {
            public class SPecials_TemplatesMetaData
            {

                    [ScaffoldColumn(false)]
                public object Key { get; set; }
                [StringLength(50)]
                public object Template_Name { get; set; }
                [StringLength(12)]
                public object Headline { get; set; }
                [StringLength(12)]
        &nbs

    Cast error when inserting record with Linq (to Sql)

      

    Hello!

    I'm getting  the following error message: 

    Unable to cast object of type 'System.Data.Linq.DataQuery`1[Username]' to type 'Username'.

    I've been searching but can't find a solution.  This particular table has 4 columns. The first column is the int indentifier.  Column 2 is "username" (varchar50) and is the primary key.  Column3 is "userID" (uniqueidentifier) and column 4 is "active" (varchar5) .

    Try
                Dim dc As New DataClassesDataContext
                Dim c3 As New Username With {.userID = userGuid, _
                                        .username = userCustomName, _
                                        .active = "False"}
    
                dc.Usernames.InsertOnSubmit(c3)
                dc.SubmitChanges()
    
            Catch ex As Exception
                Throw ex
            End Try

     



    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