Employers - Post Free Jobs
Forum guidelines
  • Home
  • »
  • C# Language
  • »
  • System.InvalidCastException: Specified cast is not valid.
AuthorQuestion
System.InvalidCastException: Specified cast is not valid.
Posted on: 07 Apr 2008
Hi, I get the following error when i run my script and i dont know what the problem could be:
System.InvalidCastException: Specified cast is not valid.
at System.Data.SqlClient.SqlBuffer.get_Int32()
at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)

Here is the code am running:

SqlConnection conn = new SqlConnection("server=(local);database=pubs;uid=admin;pwd=dbs4ever;");
string query = "select * from authors";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader;
reader = cmd.ExecuteReader();

ArrayList response = new ArrayList();
while (reader.Read())
{
Authors author = new Authors();
author.au_id = reader.GetInt32(0);
author.au_lname = reader.GetString(1);
author.au_fname = reader.GetString(2);
response.Add(author);
}
reader.Close();
conn.Close();

return response;
}

public class Authors
{
public int au_id;
public string au_lname;
public string au_fname;
}

i will appreciate your help.

AuthorReply
Re: System.InvalidCastException: Specified cast is not valid.
Posted on: 07 Apr 2008  
Check if the author_id in your sql server data base is type of integer
otherwise, I propose another code version, I suppose that there are more than one author in fact so:

SqlConnection oConnection = new SqlConnection("...");//Put your connection string instead of  ...
            SqlCommand oCommand = new SqlCommand("Select...", oConnection);
            SqlDataReader reader;
            oConnection.Open();
            ArrayList AuthorsList = new ArrayList();
            try
            {
                reader = oCommand.ExecuteReader();
                try
                {
                    while (reader.Read())
                    {
                        Author oAuthor = new Author();
                        //if not converted to integer put this line
                        oAuthor.id = Convert.ToInt32(reader["dbaseFieldName1"]);
                        //else put this line instead of the above one
                        oAuthor.id = reader["dbaseFieldName1"];
                        oAuthor.lname = reader["dbaseFieldName2"];
                        oAuthor.fname = reader["dbaseFieldName3"];
                        AuthorsList.Add(oAuthor);
                    }
                }
                finally
                {
                    reader.Close();
                }
            }
            catch (SqlException caught)
            {
                MessageBox.Show(caught.Message);
            }
public class Author
    {
        public int id;
        public string fname;
        public string lname;   
    }

Every one among us was a beginner once.
http://dotnetuniver.blogspot.com/
Re: System.InvalidCastException: Specified cast is not valid.
Posted on: 07 Apr 2008  

Use Convert.ToInt32, and please be aware of the null value.



Sunny Chen


> National Certified System Analyst
> MCP/MCAD
> Consultant of China System Analyst Institution


Personal Site:
http://www.sunnychen.org

http://www.codeplex.com/gulu
http://www.codeplex.com/StoreDDD



Re: System.InvalidCastException: Specified cast is not valid.
Posted on: 07 Apr 2008  
Hi Bechir,
I did check and realized au_id is a string but now after changing and even trying your code i get the following error:

System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type Service+Authors was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write2_ArrayOfAnyType(Object o) at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayListSerializer.Serialize(Object objectToSerialize, XmlSerializationWriter writer) at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) --- End of inner exception stack trace --- at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle) at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces) at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces) at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o) at System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue) at System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream) at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues) at System.Web.Services.Protocols.WebServiceHandler.Invoke()

I think the error could be coming coz of this:
[WebMethod(Description = "Returns a DataSet containing all authors.")]
    //public DataSet GetAuthors(  )
[return:System.Xml.Serialization.XmlArrayItemAttribute(typeof(Authors))]
    public ArrayList GetAuthors()

I do not know when typeof is used and how so could that be the problem? what do i do?



Re: System.InvalidCastException: Specified cast is not valid.
Posted on: 31 Jan 2010  

I am getting a weird error message too. I dont know why I get it. But if you know please let me know. :) Thanks.
 

Server Error in '/' 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.]
   AsknowRedesign.Controllers.ChatController.get_ForcePsychicsChat() in C:\Projects\Websites\PsychicSites\Trunk\Controllers\ChatController.cs:137
   AsknowRedesign.Controllers.ChatController.SetAgentData(UserDetails Profile) in C:\Projects\Websites\PsychicSites\Trunk\Controllers\ChatController.cs:177
   AsknowRedesign.Controllers.ChatController.GoChat(String AgentId) in C:\Projects\Websites\PsychicSites\Trunk\Controllers\ChatController.cs:66
   lambda_method(ExecutionScope , ControllerBase , Object[] ) +69
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +251
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +31
   System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +88
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +534
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +534
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +856
   System.Web.Mvc.Controller.ExecuteCore() +185
   System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +221
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +599
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171



Version Information: Microsoft .NET Framework Version:2.0.50727.4200; ASP.NET Version:2.0.50727.4016

Employers - Post Free Jobs

SPONSORED BY

Offshore Software and Database Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.