我正在研究POS系统。我正在从文本框中选择产品设计,但我如何选择相同的产品价格?
public void autoFill(TextBox abc) {
SqlCommand cmd = new SqlCommand("SELECT * FROM pProduct",cnn.con);
SqlDataReader rd;
try
{
cnn.con.Open();
rd = cmd.ExecuteReader();
while (rd.Read()) {
abc.AutoCompleteCustomSource.Add(rd["Descreption"].ToString());
}
rd.Close();
cnn.con.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
答案 0 :(得分:2)
使用另一个TextBox
作为价格
public void autoFill(TextBox abc, TextBox prc) {
SqlCommand cmd = new SqlCommand("SELECT * FROM pProduct",cnn.con);
SqlDataReader rd;
try
{
cnn.con.Open();
rd = cmd.ExecuteReader();
while (rd.Read()) {
abc.AutoCompleteCustomSource.Add(rd["Descreption"].ToString());
prc.AutoCompleteCustomSource.Add(rd["Price"].ToString());
}
rd.Close();
cnn.con.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
答案 1 :(得分:0)
在Form类中添加字段:
Dictionary<string, decimal> products = new Dictionary<string, decimal>();
当然,您应该使用自己的类型而不是string
和decimal
。
从数据库读取时将数据插入字典:
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var cmd = new SqlCommand("SELECT * FROM pProduct", conn))
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string description = (string)reader["Description"];
decimal price = (decimal)reader["Price"];
products.Add(description, price);
descriptionTextBox.AutoCompleteCustomSource.Add(description);
}
}
}
请注意using
声明。即使出现例外,它也会关闭并处置资源。
订阅TextChanged
活动。
private void DescriptionTextBox_TextChanged(object sender, EventArgs e)
{
decimal price;
if (products.TryGetValue(descriptionTextBox.Text, out price))
{
priceTextBox.Text = price.ToString();
}
else
{
priceTextBox.Text = string.Empty;
}
}