如何用存储过程结果填充ListBox [英] How to populate ListBox with stored procedure results

查看:75
本文介绍了如何用存储过程结果填充ListBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Visual Studio中使用C#,如何用SqlServer存储过程填充Form ListBox(包含从一个表中选择一个列而没有where条件的选择)?

当前代码:

Using C# in Visual Studio, how to populate Form ListBox with SqlServer stored-procedure (containing select of one column from one table with no where-criteria)?

Current code:

SqlConnection conn = new SqlConnection(connectionString);
try
{
   conn.Open();
   SqlCommand cmd = new SqlCommand("pr_MySelectProcedure", conn);
   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Connection = conn;
   string tempVal = string.Empty;
   using (SqlDataReader reader = cmd.ExecuteReader())
   {
      // if (reader.HasRows == true) ... passed this test, so continue with other code
      do
      {
         // passes test: if (reader.FieldCount > 0)
         tempVal = reader[0].ToString(); // exception error here: no data present
         // also fails with: tempVal = reader["firstcolumnname"].ToString();
      } while (reader.Read());
   }
}
catch ...


谢谢!

推荐答案

您需要在尝试访问数据之前调用reader.Read().在您的示例中,您将在之后调用它.将您的"do"循环更改为"while"应该可以解决.

You need to call reader.Read() before trying to access the data. In your example you are calling it after. Change your "do" loop to a "while" should fix it.

while(reader.Read())
{
   tempVal = reader[0].ToString(); 
}


这篇关于如何用存储过程结果填充ListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆