按ENTER键后执行一些代码

时间:2013-07-27 17:18:08

标签: c# keystroke

我有ID的文本框。我希望用户输入ID,当他按下Enter键时,我从数据库中获取该特定ID的一些信息。

如何描述按键描边?

2 个答案:

答案 0 :(得分:1)

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char) Keys.Return)
    {
        ...
    }
}

答案 1 :(得分:0)

也许这可以帮到你:

public string GetSomethingFromID(string ID)
    {
        try
        {
            string cmdString = "SELECT columnName FROM tableName WHERE ID='" + ID + "'";

            SqlConnection con = new SqlConnection(connectionString);  // create your connection string and write it's name.
            con.Open();

            SqlCommand command = new SqlCommand(cmdString, con);
            SqlDataReader sdr = command.ExecuteReader();
            sdr.Read();
            string something = sdr[0].ToString();

            con.Close();
            return something;
        }
        catch
        {
            return null;
        }
    }

然后在你的textBox上按下键时:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyData == Keys.Enter)
       textBox2.Text = GetSomethingFromID(textBox1.Text);
}