W
W
White_Bambie2020-06-14 14:41:52
C++ / C#
White_Bambie, 2020-06-14 14:41:52

How to bind ListBox to database list and show values ​​in text box?

On the form ListBox and TextBox.
When the form is launched, the ListBox is filled with data from the database.

MySqlConnection con = new MySqlConnection(AppSetting.ConnectonString());
            MySqlCommand cmd;
            cmd = con.CreateCommand();
            cmd.CommandText = "SELECT * FROM patients";
            try
            {
                con.Open();
                MySqlDataReader sdr = cmd.ExecuteReader();

                // Очищаем список

                MyListBox.Items.Clear();

                // Загружаем данные
                while (sdr.Read())
                {
                    string sLastName = sdr.GetString("LastName");
                    MyListBox.Items.Add(sLastName);
                }

                // Закрываем соединение
                con.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка");
            }

What does it look like

5ee60cce30193449560067.jpeg

When you select Surnames in the ListBox, they are filled with data from the TextBox database.
MySqlConnection con = new MySqlConnection(AppSetting.ConnectonString());
            MySqlCommand cmd;
            cmd = con.CreateCommand();
            cmd.CommandText = "SELECT * FROM patients WHERE LastName='"+ MyListBox.Text +"';";
            try
            {
                con.Open();
                MySqlDataReader sdr = cmd.ExecuteReader();

                // Загружаем данные
                while (sdr.Read())
                {
                    string sLastName = sdr.GetString("LastName");
                    txt_LastName.Text = sLastName;
                }

                // Закрываем соединение
                con.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка");
            }

After choosing a surname

5ee60cf004ca0929012242.jpeg

How to bind by id?
cmd.CommandText = "SELECT * FROM patients WHERE LastName='"+ MyListBox.Text +"';";

Answer the question

In order to leave comments, you need to log in

1 answer(s)
#
#, 2020-06-14
@White_Bambie

try google:
- c# winforms binding
(and also)
- c# winforms binding ListBox - c# winforms
binding TextBox
- c# winforms binding samples
- c# binding MySql
- c# binding MySql samples
ps

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question