Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why bool.try parse not parsing value to TRUE OR FALSE

Tags:

c#

Please consider the following code.

bool somevariable;
bool.TryParse(Convert.ToString(Dataset.Tables[0].Rows[0]["SomeColumnName"]), out somevariable);
CheckBox.Checked = somevariable;

In "SomeColumnName" in dataset, I have value as 1. So I assume that this will parse this 1 as TRUE in "somevariable".

But when I try to parse this value to bool, it always returns as false.

I don't know why.

like image 567
Deepak Kumar Avatar asked Dec 01 '22 06:12

Deepak Kumar


1 Answers

From the Boolean.Parse documentation:

true if value is equivalent to the value of the Boolean.TrueString field; false if value is equivalent to the value of the Boolean.FalseString field.

1 and 0 are not equivalent to the strings "true" or "false".

Assuming your SomeColumnName is indeed a boolean field, you can do:

return Convert.ToString(Dataset.Tables[0].Rows[0]["SomeColumnName"]) == "1";

Or directly convert to boolean (thanks @Bolu):

return Convert.ToBoolean(Dataset.Tables[0].Rows[0]["SomeColumnName"]);
like image 154
Oded Avatar answered Dec 05 '22 19:12

Oded