代码之家  ›  专栏  ›  技术社区  ›  Harry47

DataTable.Select()属性:给出索引越界异常

  •  4
  • Harry47  · 技术社区  · 12 年前

    我正在尝试仅选择父ID为0的那些行

    int predecessor = Parent;
    
            StringBuilder valuePath = new StringBuilder();
            valuePath.Append(Parent.ToString());
    
    DataRow[] drPar;
    
                while (true)
                {
                    drPar = dt.Select("MenuID=" + predecessor);
                    if (drPar != null)
                    {
                        if (drPar[0]["ParentID"].ToString().Equals("0"))
                        break;
                    }
    

    drPar[0][“ParentID”].ToString().Equals(“0”)正在给我 超出限制的异常。。

    救命!

    2 回复  |  直到 12 年前
        1
  •  7
  •   Tim Schmelter    12 年前

    DataTable.Select 不返回 null 当没有匹配时 DataRow 但是一个数组 Length==0

    但除此之外,为什么只对一个语句使用“无限”循环?

    因此,这应该起作用:

    drPar = dt.Select("MenuID=" + predecessor);
    if (drPar.Length != 0)
    {
        if (drPar[0]["ParentID"].ToString().Equals("0"))
        {
           // ...
        }
    }
    
        2
  •  2
  •   Daniel Elliott    12 年前

    数组drPar必须为空才能给出此错误,因为它是您在代码中使用的唯一索引。

    尝试

     if (drPar != null && drPar.Length > 0)