单击“保存到SQL表”按钮

本文关键字:按钮 SQL 保存到 保存 单击 | 更新日期: 2023-09-27 18:28:04

我使用下面的代码试图从文本框中获取文本,并将其添加到名为"Name"的SQL表中。注释代码是默认情况下作为按钮的代码提供的代码,我试图在下面替换它。该程序运行良好,但按下按钮后SQL表不会更新,我希望您能深入了解原因。

private void nameBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
  //this.Validate();
  //this.nameBindingSource.EndEdit();
  //this.tableAdapterManager.UpdateAll(this.cLIENTDB3DataSet);
  string cmdString = "INSERT INTO Name VALUES (@val1)";
  using (connection = new SqlConnection(connectionString))
  {
    using (SqlCommand comm = new SqlCommand(cmdString,connection))
    {
      connection.Open();
      comm.Connection = connection;
      comm.CommandText = cmdString;
      comm.Parameters.AddWithValue("@val1", nameTextBox.Text);
      comm.ExecuteNonQuery();
    }
  }
}

谢谢!

单击“保存到SQL表”按钮

EDIT:您需要选择要将值放入INSERT字符串的表中的哪一列。在编辑中,我将ColName添加到插入字符串中。

原始帖子:

尝试将CommandText更改为CommandString

 private void nameBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
  //this.Validate();
  //this.nameBindingSource.EndEdit();
  //this.tableAdapterManager.UpdateAll(this.cLIENTDB3DataSet);
  string cmdString = "INSERT INTO Name (ColName) VALUES (@val1)";
  using (connection = new SqlConnection(connectionString))
  {
    using (SqlCommand comm = new SqlCommand(cmdString,connection))
    {
      connection.Open();
      comm.Connection = connection;
      comm.CommandString = cmdString;
      comm.Parameters.AddWithValue("@val1", nameTextBox.Text);
      comm.ExecuteNonQuery();
    }
  }
}