【问题标题】:executing SqlCommand statement and displaying result in a label执行 SqlCommand 语句并在标签中显示结果
【发布时间】:2013-07-31 13:10:01
【问题描述】:

我正在执行这个存储过程,我想改变它,而不是只返回所有结果然后处理它们。我想将存储过程的第三列中的信息返回并显示到我的 winforms 应用程序上的 label.text 中。我该怎么做。

public IEnumerable GetGuids(int id)
{
    using (SqlCommand _command = new SqlCommand("StoredProc"))
    {
        _command.Connection = new SqlConnection(conString);
        _command.Connection.Open();
        _command.CommandType = CommandType.StoredProcedure;
        _command.Parameters.AddWithValue("@ItemID", id);

        return _command.ExecuteReader(); 
    }
}

我想显示将在存储过程的第 3 列中返回的项目,如下所示:itemRow1/itemRow2。

【问题讨论】:

    标签: c# winforms sqlcommand


    【解决方案1】:
    public IEnumerable GetGuids(int id)
    {    
      List<string> items = new List<string>();        
      using (SqlCommand _command = new SqlCommand("StoredProc"))
      {
          _command.Connection = new SqlConnection(conString);
          _command.Connection.Open();
          _command.CommandType = CommandType.StoredProcedure;
          _command.Parameters.AddWithValue("@ItemID", id);
    
          using (var reader = _command.ExecuteReader())
          {
             while (reader.Read())
             {
                items.Add(reader[2].ToString());
             }
          }        
      }
      return items;
    }
    

    应该为你做。然后无论标签在哪里,就像

    label.Text = String.Join(",", items.ToArray());
    

    或者你想要显示它

    【讨论】:

    • List&lt;string&gt;... 的末尾是否应该有 (),我也收到一条错误消息,指出无法从 object 转换为 string for items.Add(reader[2])
    【解决方案2】:

    类似于 reader.GetDecimal(columnIndex)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-14
      • 2023-03-12
      • 1970-01-01
      • 2014-02-06
      • 2022-10-12
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多