IRohitable | Resolving "Specified cast is not valid" error while seeking a row from DataTable.

Resolving "Specified cast is not valid" error while seeking a row from DataTable.

by Rohit 22. December 2013 19:24

In a situation I had to create a Data Table manually and add columns and rows to it. Later I wanted to search for a row in this Data Table using LINQ. As soon as LINQ code was fired I got this error: "Specified cast is not valid". Below I am sharing a sample code to simulate this problem and will tell you how to get rid of this error in this particular situation I mentioned above.

Sample Code:

public partial class _Default : System.Web.UI.Page
    {
        DataTable dt = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {

            dt.Columns.Add("RowId");
            dt.Columns.Add("Amount");

            DataRow row = dt.NewRow();
            row[0] = 1;
            row[1] = 2000;

            dt.Rows.Add(row);

            GetRecord(1);
        }

        protected void GetRecord(int RowId)
        {
            var results = from row in dt.AsEnumerable()
            where row.Field<int>("RowId") == RowId
            select row;

            string FetchedRowId = results.ToArray()[0].ToString();
        }
    }



If you execute this code, you will get this error:




The root of this error lies during the creation of columns for the Data Table. Do you notice these lines:

dt.Columns.Add("RowId");
dt.Columns.Add("Amount");


Here if you don't specify the Type of column, the default type considered is 'string'. Mentioning the default type of each column solves this issue:

dt.Columns.Add("RowId", typeof(int));
dt.Columns.Add("Amount", typeof(int));

Tags: , , ,

.NET | ASP.NET | C#

Comments (1) -

Dirk Strauss
12/23/2013 2:56:26 AM #

Excellent! Thanks for the tip!

Add comment

biuquote
  • Comment
  • Preview
Loading

About Rohit Prakash

Software Craftsman and Technology Enthusiast (not a Guru).

Technical Reviewer of a book on open-source programming IDE.

My day job keeps me engaged with Microsoft Technologies (ASP.NET, C# and SQL Server) hence most of the posts are related to these technologies. I, however, love to play with other open-source technologies. I also have interest in IT Security and therefore you will find posts on Malware Analysis, Cryptography and Anti-Virus programs.

Few people have contacted me for Guest Posts. You will find these posts as well.

 

You can reach me at:

rohit [at] irohitable.com

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

LinkedIn:

in.linkedin.com/in/rohitpkhare

Twitter:

@BuzzRohit

-----------------------------------------
Google+

Search with this name: Rohit Prakash

Month List

Protected by Copyscape Web Plagiarism Software