[英]how to get data to textboxes from database by enter event of on another textbox with if condition in c#
如何通过在c#中使用if条件在另一个文本框上输入event来将数据获取到文本框
我一直试图通过按文本框的Enter键从sql数据库中获取数据,当我输入一些错误的文本时,它不会弹出或出现输入错误的消息。
private void txtProdId_TextChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(connStrng))
{
con.Open();
String strSQL = "SELECT ProdName, Volume, CostPrice From tblProduct Where ProdCode=@ProdCode";
using (SqlCommand cmd = new SqlCommand(strSQL, con))
{
cmd.Parameters.AddWithValue("@ProdCode", txtProdId.Text);
using (SqlDataAdapter DA = new SqlDataAdapter(cmd))
{
DA.SelectCommand = cmd;
try
{
DataSet DS = new DataSet();
DA.Fill(DS);
foreach (DataRow row in DS.Tables[0].Rows)
{
txtProdName.Text = row["ProdName"].ToString();
txtProdVol.Text = row["Volume"].ToString();
txtProdPrice.Text = row["CostPrice"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
谁能帮助我取得结果。
你可以尝试类似的东西吗?
private void txtProdId_TextChanged(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == Keys.Enter)
{
using (SqlConnection con = new SqlConnection(connStrng))
{
con.Open();
String strSQL = "SELECT ProdName, Volume, CostPrice From tblProduct Where ProdCode=@ProdCode";
using (SqlCommand cmd = new SqlCommand(strSQL, con))
{
cmd.Parameters.AddWithValue("@ProdCode", txtProdId.Text);
using (SqlDataAdapter DA = new SqlDataAdapter(cmd))
{
DA.SelectCommand = cmd;
try
{
DataSet DS = new DataSet();
DA.Fill(DS);
foreach (DataRow row in DS.Tables[0].Rows)
{
txtProdName.Text = row["ProdName"].ToString();
txtProdVol.Text = row["Volume"].ToString();
txtProdPrice.Text = row["CostPrice"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
在Keydown事件中使用它:
我想这是您想要的代码。
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
using (SqlConnection con = new SqlConnection(connStrng))
{
con.Open();
String strSQL = "SELECT ProdName, Volume, CostPrice From tblProduct Where ProdCode=@ProdCode";
using (SqlCommand cmd = new SqlCommand(strSQL, con))
{
cmd.Parameters.AddWithValue("@ProdCode", txtProdId.Text);
using (SqlDataAdapter DA = new SqlDataAdapter(cmd))
{
DA.SelectCommand = cmd;
DataSet DS = new DataSet();
DA.Fill(DS);
try
{
if (DS.Tables.Count > 0)
{
if (DS.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in DS.Tables[0].Rows)
{
txtProdName.Text = row["ProdName"].ToString();
txtProdVol.Text = row["Volume"].ToString();
txtProdPrice.Text = row["CostPrice"].ToString();
}
}
else
{
txtProdName.Text = String.Empty;
txtProdVol.Text = String.Empty;
txtProdPrice.Text = String.Empty;
MessageBox.Show("No record found!");
}
}
else
{
MessageBox.Show("No record found!");
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}
}
}
}
}
无需TextChanged事件。 您可以对TextBox使用KeyPress事件。
if(e.KeyCode==Keys.Enter){
if(textBox1.Text = "some string"){
//your code here...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.