My code is (Asp.Net , C#)
int index = Convert.ToInt16(e.CommandArgument);
string str = GridView2.DataKeys[index].Value.ToString();
Session["studyuid2"] = str;
The Second Line Throws me the error Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
and my gridview is
<asp:GridView ID="GridView2" runat="server" AllowPaging="True" Height="100px"
RowStyle-Height="25px" HeaderStyle-Height="30px" FooterStyle-Height="30px"
CellPadding=5 CellSpacing=5
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" EnableModelValidation="True"
Width="100%"
DataKeyNames="StudyUID"
onrowcommand="GridView2_RowCommand"
AllowSorting="True">
<RowStyle Height="25px"></RowStyle>
<Columns>
——————————-
</Columns>
<FooterStyle Height="30px"></FooterStyle>
<HeaderStyle Height="30px"></HeaderStyle>
</asp:GridView>
In situations like this it’s helpful to add more error handling. It’s unfortunate that the
ArgumentOutOfRangeExceptiondoesn’t tell you the value of the argument and the valid range. You can do it like this, and then it’ll help you debug.You could also do this by validating the index before calling
DataKeys[index], instead of relying on exception handling to catch and rethrow.