简体   繁体   中英

Specified cast is not valid while accessing column value

I am finding records in datatable. If the record matches then I want to compare value in the datarow and do some operation. Please see my code below for better explanation,

        foreach (DataRow row2  in dtTo.Rows)
        {

            DataRow[] match = dtReturn.Select("Id = " + row2["Id"]);

            if (match.Length > 0)
            {
                if (match[0]["boolInt"] == 1) // Getting error on this line
                {
                    match[0]["NewValues"] = "";
                }

            }

        }

I was getting error on below line

 if (match[0]["boolInt"] == 1)

Then resharper suggested me to cast to bool. so I changed above line to

 if( (bool) (match[0]["bClosed"] = 1))

But when I run the project I get run time error as "Specified cast is not valid" on above line. In immediate window I get value as 1 when I type ,

(match[0]["bClosed"] 

What should i do to get rid of this error?

You need to convert the value to int. You can do it like this:

if (Convert.ToInt32(match[0]["boolInt"]) == 1)

But if the column contains a value that can't be casted you wil get an error.

A better aproach would be:

int number;
bool result = Int32.TryParse(match[0]["boolInt"], out number);
if (result && number == 1)

Try this:

 if ((match[0]["boolInt"] as int?) == 1)
 {
     match[0]["NewValues"] = "";
 }

if value is null or not valid int it won't cause exception, but should be handled anyways.

According this:

No there wont be null. The field is tinyint

you code should look like this (AFAIR, tinyint in SQL server matches byte in CLR):

if ((byte)(match[0]["boolInt"]) == 1)
{
}

If you know the field type, there's no need to call Convert methods. The faster way is to cast directly to that known type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM