Reputation: 3
I am working on POS System.I am selecting product descreptions from textbox but how I select the same product price ??
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());
}
}
Upvotes: 0
Views: 86
Reputation: 14261
Add field to your Form class:
Dictionary<string, decimal> products = new Dictionary<string, decimal>();
Of course you should use your own types instead of string
and decimal
.
Insert data into dictionary while reading from database:
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);
}
}
}
Note the using
statement. It will close and dispose resources even in case of exceptions.
Subscribe to TextChanged
event.
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;
}
}
Upvotes: 0
Reputation: 7352
use another TextBox
for Price
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());
}
}
Upvotes: 2