none
How can I combine the same data found in SQL and display it in the textbox? RRS feed

  • Question

  • My code is shown blow.

    My problem is from the database I can search many qualified mail address. Some mail address is the same. I only need one mail address to show in the textbox.

    How can I do it?Thanks!

                    SqlCommand cmd = new SqlCommand("select email from gauge" +    "where Date= '" + time + "'", conn);
                    SqlDataReader dr = cmd.ExecuteReader();
                    while(dr.Read())
                    {
                        textBox4.Text += dr[0].ToString() + ",\n";
                    }
                    dr.Close();

    Thursday, May 24, 2018 2:49 AM

Answers

  • Use if instead of while, or use ‘SELECT TOP(1) email FROM …’. Make sure there is a space before “where”. You can also add an ‘ORDER BY Date DESC’ to get the most recent data, for example.

    If you actually want to show many emails, but avoid duplicates, then use ‘SELECT DISTINCT email FROM …’.

    And use parameterised queries, by the way.

    • Edited by Viorel_MVP Thursday, May 24, 2018 5:04 AM
    • Marked as answer by ZXFzhu Thursday, May 24, 2018 6:00 AM
    Thursday, May 24, 2018 5:00 AM

All replies

  • while(dr.Read())
     {
        textBox4.Text += dr[0].ToString() + ",\n";
        break;
     }
    

    break out of the while loop...
    Thursday, May 24, 2018 3:44 AM
  • Use if instead of while, or use ‘SELECT TOP(1) email FROM …’. Make sure there is a space before “where”. You can also add an ‘ORDER BY Date DESC’ to get the most recent data, for example.

    If you actually want to show many emails, but avoid duplicates, then use ‘SELECT DISTINCT email FROM …’.

    And use parameterised queries, by the way.

    • Edited by Viorel_MVP Thursday, May 24, 2018 5:04 AM
    • Marked as answer by ZXFzhu Thursday, May 24, 2018 6:00 AM
    Thursday, May 24, 2018 5:00 AM