listbox with bank records

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 it has in the database. Bank: 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 do I not add a regit item again when I see it?

    
asked by anonymous 13.03.2017 / 14:15

2 answers

1

First you have to swap the IF for WHILE to go through all records, and to not insert repeated records your query should only bring up 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")));


                }
            }
        }
    
13.03.2017 / 15:31
2

Change if to while

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