【问题标题】:index out of range exception was unhandled in c# [duplicate]在c#中未处理索引超出范围异常[重复]
【发布时间】:2014-07-23 09:14:25
【问题描述】:

这是我检索当前插入的 product_ID 的代码,但我在这里遇到了异常 - “索引超出范围”Product_ID

    public int GetProductIDD()
    {
        int productID = 0;

        con.Open();
        string str = "SELECT MAX(Product_ID) FROM AddProduct";
        cmd = new SqlCommand(str, con);
        SqlDataReader rd = cmd.ExecuteReader();

        while (rd.Read())
        {
            productID = Convert.ToInt32(rd["Product_ID"]);
        }

        return productID;
    }

我的数据库表AddProduct如下-

Product_ID   Product_Name  Vendor_ID
-----------------------------------------
1            asd           3 

提前谢谢...

【问题讨论】:

  • 你确定你的查询是正确的吗?直接在 SQL Server 上运行会得到哪个输出?
  • 是的,查询是正确的,当在 sql server 上执行查询时,我得到了 o/p 为 1
  • 问题是您的输出不包含名为“ProductT_ID”的列。在 SQL Server 上执行查询,你就会明白我的意思了。
  • 除此之外...您为什么还要尝试获取此信息?做这样的事情通常表明有问题的设计或对数据的误解。

标签: c# sql .net sql-server-2008 c#-4.0


【解决方案1】:

尝试使用别名:

string str = "SELECT MAX(Product_ID) as Product_ID FROM AddProduct";

分析:

根据您的查询,结果将类似于:

MAX(Product_ID)
1

您正试图从结果中获取Product_ID 字段。

使用别名,结果如下:

Product_ID
1

【讨论】:

  • 非常感谢@Raging Bull 它有效
  • 但是我的代码在 sql server 上得到 o/p 时到底有什么错误
  • 见分析部分。
【解决方案2】:

如果您的查询返回单个结果,那么它在 C# OutPut 中也应该是正确的输出。

检查您的数据阅读器,它首先具有条目。

if (rd.HasRows)
{
    while (rd.Read())
    {
        productID = Convert.ToInt32(rd["Product_ID"]);
    }
}

【讨论】:

  • Op 找到答案并被接受
  • 没问题。把它当作一个建议。我现在没有足够的声誉来发表评论
猜你喜欢
  • 2012-02-09
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 2012-08-07
相关资源
最近更新 更多