用sql查询结果填充listBox
本文关键字:填充 listBox 结果 查询 sql | 更新日期: 2023-09-27 18:02:43
我试图用查询生成的值填充一个列表框,代码运行没有任何问题,但列表框不显示任何结果,我做错了什么,有没有什么缺失?
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();
}
}
如果您的代码列是字符串类型,则
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();
}
同样要添加所有值,使用while而不是if来遍历读取器中的所有记录。并且在using语句之后关闭连接。
我在这里对你的代码做了一些假设,"代码"是一个数字吗?如果没有,请尝试:
String sql = "SELECT * FROM products where code = '"+textBox1.Text+"'";
?