Skip to main content
 首页 » 编程设计

c#之获取用户名以显示在另一个表单的标签上。需要解释

2024年02月13日14落叶无声

我有 2 个表单 Login 和 UserForm。

在我的 Login 表单上,我有 2 个文本框控件,第一个用于用户名 (txtUser),第二个用于密码 (txtPass)。我还有一个名为 login 的按钮。

在我的 UserForm 上,我有一个名为 label1 的标签。

我想从 Login 中获取用户名的文本,以在 UserForm 的表单加载时显示在标签上。

请教我怎么做。

登录代码在这里:

public partial class Login : Form 
{ 
    UserForm _userform = new UserForm(); 
    Admin _Adminform = new Admin(); 
 
    public Login() 
    { 
        InitializeComponent(); 
    } 
 
    private void loginscs_Click(object sender, EventArgs e) 
    { 
        try 
        { 
            string userNameText = txtUser.Text; 
            string passwordText = txtPass.Text; 
            string isAdmin = "yes"; 
            string isNotAdmin = "no"; 
 
            if (!(string.IsNullOrEmpty(txtUser.Text)) && !(string.IsNullOrEmpty(txtPass.Text))) 
            { 
                SqlConnection SCScon = new SqlConnection(); 
                SCScon.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"; 
                SqlCommand cmd = new SqlCommand("SELECT ISNULL(SCSID, '') AS SCSID, ISNULL(SCSPass,'') AS SCSPass, ISNULL(isAdmin,'') AS isAdmin FROM SCSID WHERE SCSID='" + txtUser.Text + "' and SCSPass='" + txtPass.Text + "'", SCScon); 
 
                SCScon.Open(); 
                SqlDataReader dr = cmd.ExecuteReader(); 
 
                if (dr.Read()) 
                { 
                    if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) && 
                        this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) && 
                        this.CompareStrings(dr["isAdmin"].ToString(), isAdmin)) 
                    { 
                        MessageBox.Show("Hello " + txtUser.Text, "Admin", MessageBoxButtons.OK, MessageBoxIcon.Information); 
                        _Adminform.Show(); 
                        this.Hide(); 
                    } 
                    else if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) && 
                        this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) && 
                        this.CompareStrings(dr["isAdmin"].ToString(), isNotAdmin)) 
                    { 
                        MessageBox.Show("Welcome " + txtUser.Text, "User"); 
                        _userform.Show(); 
                        this.Hide(); 
                    } 
                } 
                else 
                { 
                    MessageBox.Show("Wrong ID/Pass"); 
                } 
                SCScon.Close(); 
            } 
        } 
        catch (Exception ex) 
        { 
            MessageBox.Show("error2" + ex); 
        } 
    } 
 
    private bool CompareStrings(string string1, string string2) 
    { 
        return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false; 
    } 
} 

请您参考如下方法:

好吧,我建议做几件事

  • 不要在登录表单中保留用户表单。登录失败直接退出应用,登录成功显示主窗体
  • 将数据访问逻辑与 UI 逻辑分开
  • 要将用户名传递给 UserForm 创建接受用户名字符串的 UserForm 构造函数

应用程序启动代码看起来像

static void Main() 
{ 
    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 
    Login login = new Login(); 
    if (login.ShowDialog() != DialogResult.OK) 
        return; 
 
    User user = login.User; 
    Form mainForm = user.IsAdmin ? (Form)new Admin() : new UserForm(user.Name); 
    Application.Run(mainForm); 
} 

因此,正如您已经注意到的,我创建了类 User 来保存与用户信息(密码除外)相关的信息:

public class User 
{ 
    public string Name { get; set; } 
    public bool IsAdmin { get; set; } 
} 

接下来,我在登录表单上分离了数据访问(移至存储库类)和 UI:

public partial class Login : Form 
{ 
    public Login()  
    {  
       InitializeComponent();  
    } 
 
    public User User { get; private set; } 
 
    private void btnLogin_Click(object sender, EventArgs e) 
    { 
        var repository = new UserRepository(); 
        User = repository.GetUser(txtUser.Text, txtPass.Text); 
        if (User == null) 
        { 
            MessageBox.Show("Wrong ID/Pass"); 
            DialogResult = DialogResult.Cancel; 
            return; 
        } 
 
        if (User.IsAdmin)             
            MessageBox.Show("Hello " + User.Name, "Admin",  
                            MessageBoxButtons.OK, 
                            MessageBoxIcon.Information);             
        else             
            MessageBox.Show("Welcome " + User.Name, "User"); 
 
        DialogResult = DialogResult.OK; 
    } 
 
    private void RequiredTextBox_Validating(object sender, CancelEventArgs e) 
    { 
        TextBox textBox = (TextBox)sender; 
        if (String.IsNullOrEmpty(textBox.Text)) 
        { 
            errorProvider.SetError(textBox, "Required"); 
            return; 
        } 
 
        errorProvider.SetError(textBox, ""); 
    } 
} 

我已经使用控件验证来检查文本框中是否输入了数据(您应该将两个文本框都订阅到 RequiredTextBox_Validating 事件并向此表单添加 ErrorProvider 组件)。接下来是数据访问。您当前的代码是 SQL Injection 的不错目标攻击。您应该使用参数将数据传递到数据库:

public class UserRepository 
{ 
    // NOTE: Use <connectionStrings> section in App.config to store connection string 
    private string connectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"; 
 
    public User GetUser(string userName, string password) 
    { 
        using (var conn = new SqlConnection(connectionString)) 
        using (var cmd = conn.CreateCommand()) 
        { 
            cmd.CommandText = @"SELECT ISNULL(SCSID, '') AS SCSID,  
                                       ISNULL(SCSPass,'') AS SCSPass,  
                                       ISNULL(isAdmin,'') AS isAdmin  
                                FROM SCSID  
                                WHERE SCSID = @userName ANDnd SCSPass = @password"; 
            cmd.Parameters.AddWithValue("@userName", userName); 
            cmd.Parameters.AddWithValue("@password", password); 
 
            conn.Open(); 
            SqlDataReader reader = cmd.ExecuteReader(); 
            if (!reader.Read()) 
                return null; 
 
            User user = new User(); 
            user.Name = userName; 
            user.IsAdmin = reader["isAdmin"].ToString() == "yes"; 
            return user; 
        } 
    } 
}