[英]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.