W
W
White_Bambie2020-06-13 15:27:29
MySQL
White_Bambie, 2020-06-13 15:27:29

How to populate TextBox from database using listbox?

There are several TextBox and ListBox components on the form. The data is loaded into the ListBox from a remote database built with PHPMyAdmin.

MySqlConnection con = new MySqlConnection(AppSetting.ConnectonString()); // Подключился к базе
con.Open();
MySqlCommand cmd;
cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM patients";
MySqlDataReader sdr = cmd.ExecuteReader();
DataTable dtRecords = new DataTable();
 dtRecords.Load(sdr);
//Заполнил ListBox
MyListBox.DataSource = new BindingSource(dtRecords, null);
MyListBox.DisplayMember = "LastName";
MyListBox.ValueMember = "id";

When the user selects an item in the listbox and clicks on it, the textbox from the database should be populated. I think this can be done by id, but I don’t understand how.
For example: Selects "Ivanov". The textbox_LastName is loaded with LastName from the table field, textbox_FirstName = FirstName and so on.
Before pressing:
5ee4c5c719111666786258.jpeg

After pressing:
5ee4c5eaf1f98606425308.jpeg

Answer the question

In order to leave comments, you need to log in

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

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("Ошибка");
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question