c# - 登录到第二个表单后如何传递名称变量
问题描述
我正在创建一个程序,该程序涉及用户登录 Form1 以访问 Form2。在 Form2 中,顶部的 Label 需要显示用户的名字和职位。因此,我必须将名称和位置变量从 Form1 传递到 Form2 才能显示它。不幸的是,当我尝试这样做时,它不会显示。
目前,该程序设置为检查数据库中输入的登录凭据,而 OleDBDataReader 查找与这些凭据关联的名称和位置。我尝试声明一个公共静态字符串以便将变量传递给 Form2,但它只返回一个空值。
在 Form 1 的 Button_Click 方法上方:
private string _name;
public string name
{
get
{ return _name; }
set
{ _name = value; }
}
private string _position;
public string position
{
get
{ return _position; }
set
{ _position = value; }
}
在 Button_Click 方法下的 Form1 上:
try
{
if (textBox1.Text == string.Empty || textBox2.Text == string.Empty)
{
MessageBox.Show("Invalid! Please enter a valid Username and/or Password.");
}
cmd = new OleDbCommand("SELECT * FROM Staff Where Username='" + textBox1.Text + "' AND Password='" + textBox2.Text + "'", sql);
if (sql.State == ConnectionState.Closed)
{
sql.Open();
i = (int)cmd.ExecuteScalar();
}
using (OleDbDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
_name = (read["FirstName"].ToString());
_position = (read["Position"].ToString());
}
}
sql.Close();
if (i > 0)
{
MainHub enter = new MainHub();
this.Hide();
enter.Show();
}
else
{
MessageBox.Show("Invalid! Please enter the correct username or password.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
最后,在 Form2 上:
Form1 f=new Form1();
string name = f.name;
string position = f.position;
Label2.Text = "Welcome! Now logged in as User " + name +" ("+ position + ").";
我希望 Label2 阅读“欢迎!现在以 [插入名称]([插入位置])登录。” 相反,它只是将这些名称和位置插槽留空。
解决方案
您可以创建一个类并使用静态变量,例如:创建一个名为“G”的类并在其上写入一个变量:
public static string name = '';
然后您可以在需要时从您的应用程序访问它!
G.name = "Your Name";
推荐阅读
- applescript - 未加载“运行 AppleScript”操作,因为它的签名无效
- java - android studio:失败:构建失败并出现异常
- xslt - XSLT 3.0 xsl:mode on-no-match="shallow-skip"
- php - 如果产品描述为空,WooCommerce 如何隐藏“描述”选项卡
- javascript - Axios 是否支持与原生 fetch() 相同的“keepalive”功能?
- android - 与正确显示文本的虚拟设备相比,为什么我的文本在 Google 商店中消失了?
- python - 使用python解析getEmailActivityUserDetail报告
- spring - 如何跟踪 WebClient POST/GET 请求的进度 - Spring Boot?
- reactjs - Is there a way to force tab unmount in ChakraUI tabs component?
- jira - 在现有 Confluence 应用程序中更改指向 Jira OAuth 的链接