Question

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;
Was it helpful?

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();

OTHER TIPS

Just ignore this line inside the loop

myreader.Read();

when you use this in the condition of while(myreader.Read()) it starts reading it. so don't call it again in side the loop. that's what your mistake is.

if (myreader.HasRows)
{
    while (myreader.Read())
    {
        stSymbols = stSymbols +  myreader["symbol"].ToString() + " ";
    }
} 

And you're good to go

if (myreader.HasRows)
{
    while (myreader.Read())
    {
        stSymbols = stSymbols +  myreader["symbol"].ToString() + " ";
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top