listbox with database records

Asked

Viewed 122 times

1

With this code I create an item in the listbox with the id number, I would like it to create an item for each id record you have in the database. Database: Mysql Code: UWP C#

 using (_connection = new MySql.Data.MySqlClient.MySqlConnection("Database=roubo_furto; Data Source=localhost;User Id=test;Password=1234;SslMode=None;"))
        {
            System.Text.EncodingProvider ppp;
            ppp = System.Text.CodePagesEncodingProvider.Instance;
            Encoding.RegisterProvider(ppp);

            _connection.Open();
            var cmd = new MySqlCommand("SELECT id FROM teste", _connection);

            using (var reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {

                    listBox.Items.Add(("Registro: " +reader.GetString("id")));


                }
            }
        }

How to make sure you don’t add a section item again when you already hear it?

2 answers

2

Exchange the if for while

while (reader.Read())
{
  listBox.Items.Add(("Registro: " +reader.GetString("id")));
}

1


first you have to exchange the IF for WHILE to go through all the records, and not to enter repeated records your query should bring only non-repeated records, using the DISTINCT keyword.

using (_connection = new MySql.Data.MySqlClient.MySqlConnection("Database=roubo_furto; Data Source=localhost;User Id=test;Password=1234;SslMode=None;"))
        {
            System.Text.EncodingProvider ppp;
            ppp = System.Text.CodePagesEncodingProvider.Instance;
            Encoding.RegisterProvider(ppp);

            _connection.Open();
            var cmd = new MySqlCommand("SELECT distinct id FROM teste", _connection);

            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {

                    listBox.Items.Add(("Registro: " +reader.GetString("id")));


                }
            }
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.