将Form1的文本框值传递给Form2按钮

3
我在我的项目中有两个表单(Form1和Form2)。
在Form1中,我有两个文本框,就像“登录”表单一样,要求用户输入用户名(textboxUsername)和密码(textboxPassword)。当用户登录后,Form2弹出。
现在,在Form2中,我有一个button1和dataGridView1。当我按下button1时,我想显示在Form1中输入的所选用户(textboxUsername)。
我想根据保存在SQL Server中的用户名获取该用户。
Form2 button1代码:
 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);

这个问题的基本答案是不要这样做。创建一个用户类并通过事件进行链接(最好还有一个接口),然后你就可以让两个表单都“知道”登录接口,而彼此之间互相不知道。 - Tony Hopkinson
2个回答

4

在 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语句,而不是使用一对引号正确替换单引号)

谢谢!现在我可以获取在Form1中输入的所选客户。 :) - user2969489
现在在Form2中,已登录的用户有一个名为Money的列。那么我能否创建一个文本框,在其中输入一个值(例如50),并根据当前登录的用户从数据库中提取它?如果此用户的Money列有100美元,在我提取50美元时,数据库中剩余50美元?请帮忙,谢谢! - user2969489
这个问题有点难以回答。我建议您准备一个带有代码示例的新问题并发布它。这样,您会比直接在这里询问更容易引起注意,因为只有我会被通知到您的新问题。 - Steve

0
一个新的数据库请求是不必要的,因为您已经在表单中有了用户名,您只需要通过适当的构造函数将其发送到Form2即可:
在Form2中,添加一个新的构造函数:
public void Form2 (String userName){...}

在Form1中:
Form 2 = new Form2 (this.textBoxUsername.Text)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接