Search code examples
c#mysqlmysqldatareader

c# mysql query with select distinct column


I am trying to put the DISTINCT rows (which is a small string) in a string variable targeting a textbox, but it only returns some of the rows with different content in the column. I used similar code but targeting a datagridview and works ok. I tried different approaches, where am I wrong?

stConsulta = "SELECT distinct symbol from ticks";
MySqlCommand MyCmd = new MySqlCommand(stConsulta,cnn);
MyCmd.Connection = cnn;
MyCmd.CommandText = stConsulta;
MySqlDataReader myreader = MyCmd.ExecuteReader();
if (myreader.HasRows)
{
    while (myreader.Read())
    {
        myreader.Read();
        stSymbols = stSymbols +  myreader.GetString("symbol") + " ";
    }
}                        
cnn.Close();
textBox1.Text = stSymbols;

Solution

  • Do not call myReader.Read() twice, for starters. You're skipping every other row.

    You indicated there aren't many rows, but you may also want to use a StringBuilder for efficiency.

    ...
    var stSymbols = new StringBuilder();
    
    while (myreader.Read())
        stSymbols.Append(myreader.GetString("symbol") + " ");
    
    ...
    textBox1.Text = stSymbols.ToString();