Getting Error Msg - Cannot implicitly convert type 'string' to 'bool'

淺唱寂寞╮ 提交于 2019-11-28 06:39:38

问题


I am checking for values in a textbox to trigger a conditional statement, but am getting error messages.

if (txtAge.Text = "49") || (txtAge.Text = "59")
{
    txtNote.Text = "A valid picture ID must be submitted";
}

The error message I am getting is Cannot implicitly convert type 'string' to 'bool'

How can I resolve this?


回答1:


When you type this:

if (txtAge.Text = "49")

This basically is assigning "49" to txtAge.Text, and then returning that value as a string (equal to "49").

This is the same, essentially, as doing:

string tmp = txtAge.Text = "49";
if (tmp) { //...

However, you cannot do "if (stringExpression)", since an if statement only works on a boolean. You most likely wanted to type:

if (txtAge.Text == "49" || txtAge.Text == "59")
{



回答2:


In the if statement replace = by ==.

You're using the assignment operator instead of the equals comparison.

The syntax for the if statement is also not correct. Check if-else (C# Reference).




回答3:


you cannot use "=" to compare strings. in this case you could use txtAge.Text.comparedTo("49") == 0 and so on




回答4:


Need to use == instead of =. Former is used for comparison while the later is for assignment.

A better way is to use Equals method

if (txtAge.Text.Equals("49") || txtAge.Text.Equals("59"))
{ 
}



回答5:


You are missing ='s. Also, you may need another set of Brackets around the whole if statement.



来源:https://stackoverflow.com/questions/2357354/getting-error-msg-cannot-implicitly-convert-type-string-to-bool

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!