Harry47
Harry47

Reputation: 101

DataTable.Select() Property: Giving Index Out of Bound Exception

I'm trying to select only those rows which have Parent 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") is giving me Out of Bound exception ..

Help Please !

Upvotes: 4

Views: 3246

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460108

DataTable.Select does not return null when there's no matching DataRow but an array with Length==0.

But apart from that, why are you using an "infinite" loop for only one statement?

So this should work:

drPar = dt.Select("MenuID=" + predecessor);
if (drPar.Length != 0)
{
    if (drPar[0]["ParentID"].ToString().Equals("0"))
    {
       // ...
    }
}

Upvotes: 7

Daniel Elliott
Daniel Elliott

Reputation: 22857

The array drPar must be empty to give this error as it is the only index you use in your code.

Try

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

Upvotes: 2

Related Questions