【问题标题】:Insert records by user who's connected Winforms按连接 Winforms 的用户插入记录
【发布时间】:2016-11-10 20:53:15
【问题描述】:

我有一个表单 (F1),用户将在其中提供他们各自的凭据 username 和 password 。

成功登录后,控件移动到客户端表单 (F2) 并在其标签中显示欢迎用户名。

客户表格包含:

  1. 标签和文本框(名称、地址、功能、...)
  2. 按钮插入
  3. DataGridView 绑定到数据库(名称、地址、函数、..、UserId)

现在,我想插入一个客户端。

填充文本框后,我想添加一个客户端显示它由已连接的用户添加。

例如:如果我在添加客户端后使用用户名 Rose 登录,请在我的 datagridView 中显示我由 Rose 添加的插入行。

我的登录代码并将用户名传递给客户表单

  private void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            //textBox2.Text = Encrypt(textBox2.Text);
            SqlConnection con = new SqlConnection("Data Source=User-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True");
            SqlDataAdapter sda = new SqlDataAdapter("select Username from [User] where Username='" + textBox1.Text + "' and Password='" + textBox2.Text + "'", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            if (dt.Rows.Count == 1)
            {
                this.Hide();
                Client c = new Client(dt.Rows[0][0].ToString());
                v.Show();
            }
            else if (dt.Rows.Count > 1)
            {
                MessageBox.Show("Nom d'utilisateur et Mot de passe dupliqué !");
            }
            else
                MessageBox.Show("Nom d'utilisateur ou Mot de passe incorrecte !");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

这是我的插入代码:

 public Client(string username)
    {
        InitializeComponent();

       lblUser.Text = username;

        DisplayData();
        FillData();

    }
private void button1_Click(object sender, EventArgs e)  
  {  
      if (  comboBox2.SelectedValue != null && textBox1.Text != string.Empty && textBox2.Text != string.Empty && textBox4.Text != string.Empty)  
      {  
          string cmdStr = "Insert into Client  (idUser,name,address,function,telephone,commentaire)values (@idUser,@name,@,address,@function,@telephone,@commentaire)";  
          SqlConnection con = new SqlConnection("Data Source=User-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True");  
          SqlCommand cmd = new SqlCommand(cmdStr, con);  
          con.Open();  

         //The problem in the line below how Can I get the id of username,Error cannot convert string Rose to int.  
          cmd.Parameters.AddWithValue("@idUser",label.Text);  
          cmd.Parameters.AddWithValue("@name", (comboBox2.SelectedValue));  
          cmd.Parameters.AddWithValue("@,address", textBox1.Text);  
          cmd.Parameters.AddWithValue("@function", textBox2.Text);  
          cmd.Parameters.AddWithValue("@telephone", textBox4.Text);  
          cmd.Parameters.AddWithValue("@commentaire",txtArchive.Text);  


          int LA = cmd.ExecuteNonQuery();  
          con.Close();  
          MessageBox.Show("Le Client a été ajouter avec succés !","Saisie Rendez-vous", MessageBoxButtons.OK, MessageBoxIcon.Information);  
          DisplayData();  
          ClearData();  
      }  
      else  
      {  
          MessageBox.Show("Vérifier que tous les champs sont remplis !","Erreur",MessageBoxButtons.OK,MessageBoxIcon.Information);  
      }  
  }  

我无法弄清楚如何做到这一点,我对 c# 很陌生,正在努力学习。

提前致谢。

【问题讨论】:

  • 你的问题不清楚,具体是哪部分有问题?
  • 我在上面代码中的注释中解释了我的问题,我想添加一个新客户并想知道它是由谁添加的(已连接的用户 = Rose)?
  • 哦,实际问题在代码注释中 - 是的,这不是最好的地方!
  • 您可以记住登录用户并将其传递给form2,这是您想要的吗?
  • 您是否有一个用户表,其中每个用户的Username 都有Id

标签: c# winforms


【解决方案1】:

当检查登录时,这样写你的查询:

SELECT [Id], [UserName] from [Users] WHERE [UserName]=@UserName AND [Password]=@Password

然后存储登录成功时从查询中获得的[Id][UserName](结果集中包含一条记录)。这样您就可以在每次需要时使用登录用户的用户名和 id。

例如:

var cmd = @"SELECT [Id], [UserName] FROM [Users] " +
          @"WHERE [UserName] = @UserName AND [Password] = @Password";
var cn = @"Data Source=User-PC\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True";
var da = new SqlDataAdapter(cmd, cn);
da.SelectCommand.Parameters.AddWithValue("@UserName", textBox1.Text);
da.SelectCommand.Parameters.AddWithValue("@Password", textBox2.Text);
var dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 1)
{
    int id = dt.Rows[0].Field<int>("Id");
    string userName = dt.Rows[0].Field<string>("UserName");
    //...
}

注意:

  • 您应该使用参数化查询来防止 SQL 注入攻击。

【讨论】:

  • 结果DataTable的第一条记录同时包含IdUserName。 dt.Rows[0]。例如int id = dt.Rows[0].Field&lt;int&gt;("Id");string userName = dt.Rows[0].Field&lt;int&gt;("UserName");
  • 如果我运行我的程序并尝试登录,它会显示一个错误:对象引用未定义
  • 看来您知道如何运行参数化命令,所以我没有将其添加到答案中。当然,您可以自己解决对象空引用异常。我的答案中没有任何代码。您需要更多帮助吗?
  • 我添加了一个示例,说明如何将参数化查询与数据适配器一起使用。
  • 您在应用该解决方案时还需要其他帮助吗?
【解决方案2】:

首先,参数化您的登录查询!目前你很容易受到 SQL 注入攻击!以免您受到Little Bobby Tables 的访问。


在回答您的问题时,更改登录表单上的查询以返回用户的 ID 和用户名。

SqlDataAdapter sda = new SqlDataAdapter("select Id, Username from [User] where Username=@Username and Password=@Password", con);

现在,当您读取单个结果时,您可以从字段 0 中获取 Id,从字段 1 中获取用户名。

if (dt.Rows.Count == 1)
{
    this.Hide();
    var row = dt.Rows[0];
    int userId = (int)row[0];
    string username = (string)row[1];
    Client c = new Client(userId, username);
    v.Show();
}

还要注意在该代码中,我将两者都传递给Client 表单。更新构造函数以将两条信息保存在局部变量中:

public class Client : Form
{
    private int _userId;

    public Client(int userId, string username)
    {
        InitializeComponent();

        _userId = userId;
        lblUser.Text = username;

        DisplayData();
        FillData();
    }
}

此后,您可以在Client 表单中的任何地方使用_userId。例如。在保存按钮点击:

cmd.Parameters.AddWithValue("@idUser",_userId);  

【讨论】:

    猜你喜欢
    • 2015-09-25
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多