Sibusiso Shongwe Sibusiso Shongwe - 3 months ago 30
C# Question

Populating a listBox with sql query results

Am trying to populate a listbox with values generated by a query, the code runs without any problems but the listbox is not displaying any results, what am i doing wrong, is there anything missing??

String sql = "SELECT * FROM products where code = "+textBox1.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn); //c.con is the connection string
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
listBox1.Items.Add(reader["description"].ToString() + ": "+reader["price"].ToString());
listBox1.Refresh();
}
reader.Close();
conn.Close();
}
}

Answer

If your code column is of string type then

    String sql = "SELECT * FROM products where code = '"+textBox1.Text + "'";
    SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn); //c.con is the connection string
    using (SqlCommand cmd = new SqlCommand(sql, conn))
    {
          conn.Open();
          using (SqlDataReader reader = cmd.ExecuteReader())
          {
                while(reader.Read())
                {
                    listBox1.Items.Add(reader["description"].ToString() + ":    "+reader["price"].ToString());
                }
                reader.Close();                   
           }
           conn.Close();
     }

Also to add all values, use while instead of if to traverse all the records in the reader. And also close the connection after the using statement. I am sure the wrong sequence is causing the issue.