James
James

Reputation: 1945

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?

Upvotes: 1

Views: 2164

Answers (3)

Dennis
Dennis

Reputation: 37770

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.

Upvotes: 1

gzaxx
gzaxx

Reputation: 17600

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.

Upvotes: 1

Romano Zumbé
Romano Zumbé

Reputation: 8079

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)

Upvotes: 1

Related Questions