I am trying to loop through a datalist control (asp.net 2.0) and get the selected values. Each time this code runs, I get this error:
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
It highlights this line: int key = (int)this.dlstDemoList.DataKeys[item.ItemIndex];
Here's the code:
foreach (DataListItem item in dlstDemoList.Items)
int key = (int)this.dlstDemoList.DataKeys[item.ItemIndex];
// Do something with the value of key
// Select the sales rep assigned to this demo.
DropDownList ddl = item.FindControl("ddlSalesReps") as DropDownList;
string keyd = ((HtmlInputControl)item.FindControl("Sales_Rep_ID")).Value;
ddl.SelectedValue = keyd;
This ran perfectly before I moved it to a different page. It originally ran on ASP.NET 1.1, but now is 2.0 - so I wonder if the control is a little different or something. Regardless, there are several values that are displayed in this list.