Default.aspx
make
Default.aspx.cs
<Columns>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:DropDownList ID="typeHobby" runat="server">
<asp:ListItem style="display:none">--Select--</asp:ListItem>
<asp:ListItem Value="Sports">Sports</asp:ListItem>
<asp:ListItem Value="FineArt">Fine Arts</asp:ListItem>
<asp:ListItem Value="Other">Other</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="nameSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Details of participation">
<ItemTemplate>
<asp:TextBox ID="detailSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Distinction achieved">
<ItemTemplate>
<asp:TextBox ID="distSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Whether still intrested">
<ItemTemplate>
<asp:DropDownList ID="intrestSport" runat="server">
<asp:ListItem style="display:none">--Select--</asp:ListItem>
<asp:ListItem Value="yes">Yes</asp:ListItem>
<asp:ListItem Value="no">No</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="addHobby" runat="server" Text="Add" OnClick="ButtonAdd_Click_Hobby" CausesValidation="false" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
System.ArgumentOutOfRangeException:'指定的参数超出有效值范围。 参数名称:索引' ->在上面出现了类似上面的错误: DropDownList txh5 =(DropDownList)hobbyGrid.Rows [rowIndex] .Cells [5] .FindControl(“ intrestSport”);
(来自SetPreviousDataHobby()函数的行)
答案 0 :(得分:0)
我相信这应该为您指明正确的方向
DataGrid
的行和列从 index 0
hobbyGrid.Rows[rowIndex].Cells[5]
表示有 6 列,您认为是真的吗?
错误消息仅表示您正在访问超出数据结构限制的索引。
您可以通过columns
row[0]
验证hobbyGrid.Rows[0].Cells.Count-1;
上有多少Cells[5]
可用
OR
您还可以从int cols= dtHobbyTable.Columns.Count
答案 1 :(得分:0)
错误是因为,您正在访问从1到5的单元。因此,在Cells [5]中,它抛出范围外异常。请修改您的代码以从0开始:
DropDownList txh1 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[0].FindControl("typeHobby");
TextBox txh2 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[1].FindControl("nameSport");
TextBox txh3 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[2].FindControl("detailSport");
TextBox txh4 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[3].FindControl("distSport");
DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[4].FindControl("intrestSport");
侧面但相关的注释: 1)解决此错误后,您可能会遇到另一个问题: 在forloop之外添加数据行。因此,您基本上是在for循环中覆盖数据行并仅添加一行。如果那是您所期望的,请忽略我。否则,请将以下行移动到for循环中。
dtHobbyTable.Rows.Add(drHobbyRow);
2)另一个问题是您正在更新的项目上正在运行循环。而是在hobbyGrid.Rows.Count上具有for循环是很好的。