ASP.NETDataGrid中绑定Dropdownlist,绑定中“索引超出范围。必须为非负值并小于集合大小。”问题的解决

    技术2025-05-04  18

    把自己常用的代码记录下来,下次用的时候就省事多了。

    把自己碰到的问题记录下来,下次解决起来就省事多了。

     

     

    前台:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%" OnRowDataBound="gvChonsens_RowDataBound" DataKeyNames="m_ID,m_Unit"> <Columns> <asp:BoundField HeaderText="序号"> <ItemStyle Width="39px" /> </asp:BoundField> <asp:TemplateField HeaderText="单位"> <ItemStyle Width="70px" /> <ItemTemplate> <asp:DropDownList ID="droUnit" runat="server" Width="60"> </asp:DropDownList> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>

     

     

    后台:

    protected void gvChonsens_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DropDownList droUnit = (DropDownList)e.Row.FindControl("droUnit"); Usual.DrpBind(droUnit, "unit_ID", "unit_Name", "wms_unit", ""); droUnit.SelectedValue = this.gvChonsens.DataKeys[e.Row.RowIndex]["m_Unit"].ToString(); } }

     

    如果使用了DataKeys,就一定不要忘记DataKeyField。不然,就会像我遇到的一样,DataKeys的Count一直是0,总是提示“索引超出范围。必须为非负值并小于集合大小。”

    最新回复(0)