chamara
chamara

Reputation: 12709

"Invalid Cast" In Linq

I'm trying to filter a datatable with following code

private void Filter(string text)
    {
        int outText=0;
        if (Int32.TryParse(text, out outText))
        {
            text = string.Empty;
        }
     DataTable DT = new DataTable();
            DT = PinCDAO.GetArea().AsEnumerable().Where(r => r.Field<int>("AreaID")==Convert.ToInt32(outText) || (r.Field<string>("AreaDescription").Contains(text))).AsDataView().ToTable();

}

I'm getting the error "Specified cast is not valid".because of the code

r => r.Field<int>("AreaID")==Convert.ToInt32(outText) 

I'm sure about that AreaID column Contains Integers

plz help me to solve this.

Upvotes: 2

Views: 1655

Answers (4)

Pranay Rana
Pranay Rana

Reputation: 176956

Try out code - Handle null in you code

because "AreaID" is nullable field.

DT = PinCDAO.GetArea().AsEnumerable().Where(r => 
   (Convert.IsDBNull(r["AreaID"]) ? 0 :  Convert.ToInt32(r["AreaID"])) ==outText
  || (r.Field<string>("AreaDescription").Contains(text))).AsDataView().ToTable();

this code handles null value easily..

already answered question by me : "Specified cast is not valid" error in LINQ's orderby clause

Upvotes: 2

Akash KC
Akash KC

Reputation: 16310

You don't need conversion to int as outText already declared to int....You can simply use the outText in following way:

r => r.Field<int>("AreaID")==outText 

You can change the expresson in following way:

 r => Convert.ToInt32(r["AreaID"])==outText 

Upvotes: 1

Habib
Habib

Reputation: 223422

Remove Convert.ToInt32, outText is already parsed as int using if (Int32.TryParse(text, out outText))

DT = PinCDAO.GetArea().AsEnumerable()
          .Where(r => r.Field<int>("AreaID")==outText 
                           || (r.Field<string>("AreaDescription")
           .Contains(text))).AsDataView().ToTable();

The reason you are getting the exception could be that "AreaID" may not contain an int value

Upvotes: 1

Ebad Masood
Ebad Masood

Reputation: 2379

Variables passed as an out arguments need not be initialized prior to being passed. Moreover, outtext need not to be convert to Int32 as it is one already.

private void Filter(string text)     {      
   int outText;         
          if (Int32.TryParse(text, out outText))        
                  { 
                    // text was integer and parsed successfully.            
                    text = string.Empty;       
                   }     
 DataTable DT = new DataTable();  
           DT = PinCDAO.GetArea().AsEnumerable().Where(r => r.Field<int>("AreaID")== outText || (r.Field<string>("AreaDescription").Contains(text))).AsDataView().ToTable();  } 

Upvotes: 1

Related Questions