简体   繁体   中英

How to read data from database on textbox while auto select from another textbox in c#

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());
            }
        }

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());
            }
        }

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM