-6

我正在使用 windows 窗体应用程序 c# 我已经创建了一些文本框,我想将这些值发送到数据库,单击按钮后一切正常,但我需要在从文本框中按 enter 后将所有值输入数据库. 任何想法??

                // 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);`
4

2 回答 2

2

您可以处理控件的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()
                    }
              }                 
            }

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

于 2013-11-15T08:21:01.933 回答
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 事件之后保存到数据库中不是正确的方法。

对于您未来的问题,请提供您的代码。

于 2013-11-15T08:26:02.150 回答