将Form1 textBox值传递给Form2按钮

本文关键字:Form2 按钮 值传 Form1 textBox | 更新日期: 2024-09-25 05:00:53

我的项目中有两个表单(Form1&Form2)。

在Form1上,我有两个类似"登录"表单的文本框,要求用户输入用户名(textboxUsername)&密码(文本框密码)。当用户登录时,会弹出Form2。

现在在Form2中,我有一个button1和dataGridView1。当我按下按钮1时,我想显示我在Form1(文本框用户名)中输入的选定用户

我想根据保存在SQL Server中的用户名获取该用户。

Form2按钮1代码:

 private void button1_Click(object sender, EventArgs e)
    {
        string constring = @"Data Source=V-K';Initial Catalog=ATMKlientet;Integrated Security=True";
        SqlConnection conDataBase = new SqlConnection(constring);
        SqlCommand cmdDataBase = new SqlCommand(" select * from Clients ;", conDataBase);
        try
        {
            SqlDataAdapter sda = new SqlDataAdapter();
            sda.SelectCommand = cmdDataBase;
            dbdataset = new DataTable();
            sda.Fill(dbdataset);
            BindingSource bSource = new BindingSource();
            bSource.DataSource = dbdataset;
            dataGridView1.DataSource = bSource;
            sda.Update(dbdataset);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

在这种情况下,我想在Form2中调用Form1 textBoxUsername的部分是:

(" select * from Clients where Username='" + this.textBoxUsername + "';",  conDataBase);

将Form1 textBox值传递给Form2按钮

在Form1中,当您打开第二个表单时,可能有

 Form2 f = new Form2();
 f.ShowDialog();

在这里,您可以更改将文本框的值传递给Form2的构造函数的调用;

 Form2 f = new Form2(textBoxUserName.Text);
 f.ShowDialog();

在Form2构造函数中,您将接收此值并将其存储在类级全局变量中

public class Form2: Form
{
    private string currentUserName = string.Empty;
    public Form2(string userName)
    {
        currentUserName = userName;
    }
}

现在您可以使用内部私有变量currentUserName进行查询

附带说明一下,不要使用字符串串联来构建sql命令。始终使用参数化查询:

SqlCommand cmd = new SqlCommand("select * from Clients where Username=@uname", conDataBase);
cmd.Parameters.AddWithValue("@uname", currentUserName);
.....

使用字符串串联是危险的,因为您的代码容易受到Sql注入攻击,并且需要对字符串、小数和日期进行适当的分析。(例如,如果用户名包含一个单引号,则字符串串联将生成一个无效的SQL语句,而不会用两个引号正确替换单引号)

不需要新的DB请求,因为您已经在Form中有了用户名,您只需要通过适当的构造函数将其发送到Form2:

在Form2中,添加一个新的构造函数:

public void Form2 (String userName){...}

形式1:

Form 2 = new Form2 (this.textBoxUsername.Text)