从文本框中按Enter键后输入数据库值

时间:2013-11-15 08:17:01

标签: c# sql winforms textbox buttonclick

我正在使用Windows窗体应用程序c#i已经创建了一些文本框,我想将这些值发送到数据库,它在按钮单击后全部工作但我需要在按下回车后输入所有值到数据库一个文本框。任何的想法??

                // Adding Values to Data Base
                string mySQL = "INSERT INTO Stock_Entry VALUES ("
                    + textBox_ItemId.Text + ", '"
                    + textBox_Ctgry.Text.Trim() + "','"
                    + textBox_ItmNme.Text.Trim() + "','"
                    + textBox_UntPrc.Text.Trim() + "','"
                    + textBox_Stock.Text.Trim() + "','"
                    + dateTimePicker_StkInDat.Text.Trim() + "','"
                    + textBox_Store.Text.Trim() + "','"
                    + textBox_StlLktn.Text.Trim() + "')";

                DBConnection database = new DBConnection();
                int rslt = database.insertValues(mySQL);`

2 个答案:

答案 0 :(得分:1)

您可以处理KeyDown控件的TextBox事件来实现此目的。

示例代码:

    private void TextBox1_KeyDown(object sender, KeyEventArgs e)
            {

                if (e.KeyCode == Keys.Enter)
                {
                    // call function here to Insert TextBox1 data into database
                    InsertMyData(TextBox1.Text.ToString());    
                }
            }

            private void InsertMyData(String value1)
            {
              //Insert Data into database
              String strCon = "Data Source=(local);Initial Catalog=mydatabase;uid=uid;pwd=pwd;Integrated Security=True;";
             using (SqlConnection sqlCon = new SqlConnection(strCon))
             {
                String strCmd = "insert into mytable(value1) value(@myvalue1)";
                    using (SqlCommand sqlcommand = new SqlCommand(strCmd, sqlCon))
                    {
                    sqlCon.Open();
                    sqlcommand.Parameters.AddWithValue("@myvalue1", value1);
                    sqlcommand.ExecuteNonQuery()
                    }
              }                 
            }

如果您想了解更多信息,请告诉我您的情况。

答案 1 :(得分:0)

用于此KeyDown事件

 private void YourTextBox_KeyDown(object sender, KeyEventArgs e)
        {
 String connection= "Data Source=YourServer;Initial Catalog=YourDatabase;user=User;password=YourPassword;Integrated Security=True;";
        if (e.KeyCode == Keys.Enter)
        {
string insertCmdText = "INSERT INTO table(column1)values(@valueForColumn1)";
SqlCommand sqlCom = new SqlCommand(insertCmdText,connection);
sqlCom.Paramaters.AddWithValue("@valueForColumn1",YourTextBox.Text);
connection.Open();
sqlCom.ExecuteNonQuery();
connection.Close();
        }
    }

但是考虑在KeyPress事件之后保存到数据库中是不正确的方法。

如果您将来的问题请提供您的代码。