我的项目中有两个表单(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);
答案 0 :(得分: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 Injections攻击,并且您需要采取适当的措施来进行字符串,小数和日期解析。 (例如,如果用户名包含单引号,则字符串连接将生成无效的SQL语句,而没有用几个引号正确替换单引号)
答案 1 :(得分:0)
不需要新的DB请求,因为您已经在Form中使用了用户名,只需通过相应的构造函数将其发送到Form2:
在Form2中,添加一个新的构造函数:
public void Form2 (String userName){...}
在Form1中:
Form 2 = new Form2 (this.textBoxUsername.Text)