按下ENTER键后执行某些代码
本文关键字:代码 执行 ENTER 按下 | 更新日期: 2023-09-27 18:25:07
我有一个ID文本框。我希望用户输入ID,当他按下enter键时,我会从数据库中的特定ID中获取一些信息。
如何捕捉我所描述的关键笔划?
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char) Keys.Return)
{
...
}
}
也许这可以帮助您:
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;
}
}
然后当按下你的文本框上的键时:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyData == Keys.Enter)
textBox2.Text = GetSomethingFromID(textBox1.Text);
}