简体   繁体   中英

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

I am Getting this error System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Source Error:

Line 153: Session["Cat"] = e.CommandArgument.ToString();
Line 154:
Line 155: Session["Cat_ID"] = DataList3.DataKeys[e.Item.ItemIndex].ToString();//error
Line 156: Response.Redirect("Disp_Category.aspx?id=C"); Line 157: }

Please some one what is wrong with this code

protected void DataList3_ItemCommand(object source, DataListCommandEventArgs e)
 {
     Session["L_Id"] = ddlLanguage.SelectedValue;
     Session["Cat"] = e.CommandArgument.ToString();

     Session["Cat_ID"] = DataList3.DataKeys[e.Item.ItemIndex].ToString();
     Response.Redirect("Disp_Category.aspx?id=C");
 }

on aspx file i have this

<asp:DataList ID="DataList3" runat="server" DataKeyNames="C_Id" DataSourceID="SqlDataSource3" OnItemCommand="DataList3_ItemCommand">
                                <ItemTemplate>
                                    <table cellpadding="0" cellspacing="0" border=1 width=150>
                                        <tr>
                                            <td>
                                                <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("C_Name") %>'
                                                    Text='<%# Eval("C_Name") %>' CausesValidation="False"></asp:LinkButton></td>
                                        </tr>
                                    </table>
                                </ItemTemplate>
                            </asp:DataList><asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\New Projects\Sym\App_Data\Music.mdf;Integrated Security=True;User Instance=True"
                                ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM [Category] ORDER BY [C_Name]">
                            </asp:SqlDataSource>

You are not right. I suggest to set the id (c_id) and not the name (c_name) in CommandArgument . That's your key. In ItemCommand you can get entire record by id. Moreover:

Response.Redirect("Disp_Category.aspx?id=C");

becomes

Response.Redirect("~/Disp_Category.aspx?id=C");  //id=C? sure?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM