C# 赋值的左侧必须是变量,属性 或索引器

C# Left-Hand Side Of An Assignment Must Be a Variable, Property or Indexer

我真的找不到回答这个特定场景的帖子。另外,也许我真的很累。无论如何,我正在为 WinForms 进行登录验证。我有一个名为 DBFunctions.cs 的 class,它保存数据库连接信息等。我在 C# 中遇到了这个 "The left-hand side of an assignment must be a variable, property or indexer" 错误。请在下面找到我当前的代码。提前致谢。

namespace emsdashboard
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();

}
//Contains the SQL string and other information to process
//user login.
public object VerifyUser(string userId, string password)
{
DBFunctions dbInfo = new DBFunctions();
bool status = false;
string verifyUserQry = "SELECT * FROM Employee WHERE UserName = '" + userId    + "' AND Password = '" + password + "'";
 DataTable dt = default(DataTable);
 dt = dbInfo.OpenDTConnection(verifyUserQry);
 if (dt.Rows.Count == 1)
 {
 status = true;
 }
 return status;
 }





   //When the login button is clicked. Check to see if the user
   //entered a username and/or password. Also verify the username
   //and the password are correct, else display an error message.
   private void btnLogin_Click(object sender, EventArgs e)
   {
   if(tbxUsername.Text=="" || tbxPassword.Text=="")
   {
   MessageBox.Show("Username and Password cannot be blank", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }
    else
    {
    if (VerifyUser(tbxUsername.Text, tbxPassword.Text) = true)
    {
    this.Hide();
    }
    }

    }
    }
    }

很简单,您将 =(赋值运算符)与 ==(比较运算符)混淆了。

你会想进入

if (VerifyUser(tbxUsername.Text, tbxPassword.Text) == true)

(而不是 = true

但实际上,将布尔值与常量布尔值进行比较是一种多余的操作。

你应该只使用:

if (VerifyUser(tbxUsername.Text, tbxPassword.Text))

我试图将一个对象转换为 bool。我声明了 bool 类型的状态并返回了一个 bool,所以我需要将 public 对象更改为 public bool。代码如下:

原文:

public object VerifyUser(string userId, string password)
    {
        DBFunctions dbInfo = new DBFunctions();
        bool status = false;
        string verifyUserQry = "SELECT * FROM Employee WHERE UserName = '" + userId + "' AND Password = '" + password + "'";
        DataTable dt = default(DataTable);
        dt = dbInfo.OpenDTConnection(verifyUserQry);
        if (dt.Rows.Count == 1)
        {
            status = true;
        }
        return status;
    }

更正

public bool VerifyUser(string userId, string password)
    {
        DBFunctions dbInfo = new DBFunctions();
        bool status = false;
        string verifyUserQry = "SELECT * FROM Employee WHERE UserName = '" + userId + "' AND Password = '" + password + "'";
        DataTable dt = default(DataTable);
        dt = dbInfo.OpenDTConnection(verifyUserQry);
        if (dt.Rows.Count == 1)
        {