我创建了一个带有连接的 SQL 数据库和一个带有用户和密码的表。我设法按照指南创建了一个登录名。该代码可以正常登录,但我想要做的是在用户登录后在主表单上显示所有其他按钮。
我在主窗体中使用面板来显示第二个窗体。单击按钮会在中间面板中显示一个 UserControl。
我只想将 Button.Visible
值从 false
更新为 true
,而无需打开新的主表单。
我可以让按钮在表单加载时可见,但在我尝试设置条件时不可见。我不知道如何设置一个条件,当用户登录成功时,其他按钮设置为可见,登录按钮隐藏。
MainLogin
UserControl 中的部分代码。
我添加的 Mainmenu.Userautherised
是在登录成功时将 userID
从 TextBox 传递给 Userautherised()
表单中的 Mainmenu
方法。
if (mread.Read() == true)
{
MessageBox.Show("Login successfull");
this.Hide();
Mainmenu.Userautherised(text_userID.Text);
}
Mainmenu
中的部分代码:我这样做是为了解决问题。
我认为在用户成功登录时将 bool 设置为 true
,然后我可以调用 ShowButtons()
方法将按钮设置为可见:
public static bool Userautherised(string user)
{
bool returnValue;
string _user ="true";
string _noUser ="false";
bool _userID = bool.Parse(_user);
bool _noUserID = bool.Parse(_noUser);
}
if (user == "")
{
returnValue = _noUserID;
return returnValue;
}
else
{
returnValue = _userID;
return returnValue;
}
据我所知,我从调试中获得了 bool 值,但是当我尝试在 if
方法中使用 ShowButtons()
语句时,我不知道如何获得 bool值从 Userautherised()
到 if(Userautherised())
以在值为 true
时显示按钮。
我希望我能很好地描述这个问题。
编辑 1:
我尝试了相同的 event action
语法来获取登录用户的位置和访问权限。在 MainLogin
表单中,我添加了以下内容:
public event action<string> accESS;
public event action<string> POSITION;
string useraccess,userPosition;
然后我在 mread.Read
if 语句中添加了以下内容:
Sqlcommand cmd_get_position_access = new SqlCommand (
"SELECT,access FROM Users WHERE position = @position AND access = @access",dataconnection);
SqlParameter _position = new SqlParameter("@position",SqlDbType.NVarchar);
SqlParameter _access = new SqlParameter("@access",SqlDbType.NChar);
cmd.Parameters.Add(_position);
cmd.Parameters.Add(_access);
userPosition = mread["position"].ToString();
useraccess = mread["access"].ToString();
我在尝试调用新事件时收到 NullReferenceException
,因此我添加了以下 if-else 语句来修复它:
if (accESS == null || POSITION == null)
{
return;
}
else
{
accESS.Invoke(useraccess);
POSITION.Invoke(userPosition);
}
在 Mainmenu
按钮点击事件中:
var userLogin = new MainLogin();
panel_Main.controls.Add(userLogin);
userLogin.userLogged += UserLogged;
userLogin.accESS += Useraccess;
userlogin.POSITION += Position;
userLogin.Show();
调试时,我可以看到我从数据库表中获取了 access 值。但是,当我尝试使用带有 if 语句的方法但即使为真时也会跳过条件。我也尝试过 switch 语句,但同样的事情也会发生在案例中。它们被跳过。例如,如果管理员登录我得到 access yellow
但大小写被跳过。同样的事情发生在 if 语句条件上。 access is yellow
且条件为真但跳过 if 语句。 为什么在条件为真时跳过它们?
private void Useraccess(string access)
{
switch (access)
{
case: "yellow":
userAdmin();
break;
case: "green":
userGreen();
break;
default:
break;
}
}
编辑 2:
我发现了问题。结果是在 User 表中。访问权限设置为 nchar
数据类型,该数据类型为值添加空格。 access
得到了 string
"yellow "
。我将数据类型更改为 varchar
并解决了问题。