问题描述
我想通过输入带有txtSearch_TextChanged事件的条形码来从txtSearch检查数据库表,在txtSearch_TextChanged事件之后,我想选择所有txtSearch文本,当条形码正确时也可以使用,我也想选择全部txt,当条形码不正确时进行搜索。
private void txtSearch_TextChanged(object sender,EventArgs e)
{
try
{
String _pcode;
double _price;
double _qty;
cn.open();
cm = new sqlCommand("select * from tblProduct where barcode like '" + txtSearch.Text + "'",cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
_pcode = dr["pcode"].ToString();
_price = double.Parse(dr["price"].ToString());
_qty = double.Parse(txtQty.Text);
dr.Close();
cn.Close();
AddToCart(_pcode,_price,_qty);
txtSearch.SelectionStart = 0;
txtSearch.SelectionLength = txtSearch.Text.Length;
}
else
{
dr.Close();
cn.Close();
}
}
catch (Exception ex)
{
cn.Close();
MessageBox.Show(ex.Message);
}
}
当我键入tblProduct中的任何条形码并且txtSearch中的所有文本都将被选中时,是否希望工作;当tblProduct中没有任何条形码时,我希望txtSearch中的文本将被选中时,我尝试这样做{ dr.Close(); cn.Close(); txtSearch.SelectionStart = 0; txtSearch.SelectionLength = txtSearch.Text.Length; }它只是选择第一个数字,我还没有从代码中看到任何错误。
解决方法
private void txtSearch_TextChanged(object sender,EventArgs e)
{
try
{
// Your code
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
txtSearch.TextChanged -= txtSearch_TextChanged;
txtSearch.Text = txtSearch.Tag + txtSearch.Text;
txtSearch.Tag = txtSearch.Text;
txtSearch.SelectionStart = 0;
txtSearch.SelectionLength = txtSearch.Text.Length;
txtSearch.TextChanged += txtSearch_TextChanged;
}
private void txtSearch_KeyDown(object sender,KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Back:
//remove last character from txtSearch.Tag
txtSearch.Tag = txtSearch.Tag != null && !string.IsNullOrWhiteSpace(txtSearch.Tag.ToString())
? txtSearch.Tag.ToString().Remove(txtSearch.Tag.ToString().Length - 1)
: string.Empty;
break;
case Keys.Delete:
txtSearch.Tag = string.Empty;
break;
// handle other keys here
}
}
,
这是解决方案,谢谢您的时间
private void txtSearch_TextChanged(对象发送者,EventArgs e) { 尝试 { 如果(txtSearch.Text.Trim()。Length == 1) { tmrDelay.Enabled = true; tmrDelay.Start(); tmrDelay.Tick + =新的EventHandler(tmrDelay_Tick); } } 抓住(前例外) { MessageBox.Show(ex.Message); }
}
void tmrDelay_Tick(object sender,EventArgs e)
{
try
{
tmrDelay.Stop();
string strCurrentString = txtSearch.Text.Trim().ToString();
if (strCurrentString != "")
{
String _pcode;
double _price;
double _qty;
cn.Open();
cm = new SqlCommand("select * from tblProduct where barcode like '" + txtSearch.Text + "'",cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
_pcode = dr["pcode"].ToString();
_price = double.Parse(dr["price"].ToString());
_qty = double.Parse(txtQty.Text);
dr.Close();
cn.Close();
AddToCart(_pcode,_price,_qty);
}
else
{
MessageBox.Show("soory the bar code does not exist","",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
dr.Close();
cn.Close();
txtSearch.Text = "";
}
txtSearch.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}