首页 > 解决方案 > 登录到第二个表单后如何传递名称变量

问题描述

我正在创建一个程序,该程序涉及用户登录 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 阅读“欢迎!现在以 [插入名称]([插入位置])登录。” 相反,它只是将这些名称和位置插槽留空。

标签: c#sqldatabaselogin

解决方案


您可以创建一个类并使用静态变量,例如:创建一个名为“G”的类并在其上写入一个变量:

public static string name = '';

然后您可以在需要时从您的应用程序访问它!

G.name = "Your Name";

推荐阅读