分页时ListView的ItemDataBound中丢失的DataKey值

时间:2013-11-11 03:57:11

标签: asp.net vb.net listview paging itemdatabound

我通过ItemDataBound将数据绑定到嵌套在ListView中的GridView,当我分页ListView时,它丢失了datakey值。 这是DataBound事件:

Protected Sub gvResult_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles gvResult.ItemDataBound
        If e.Item.ItemType = ListViewItemType.DataItem Then
            Dim dbSrc As New SqlDataSource
            dbSrc.SelectParameters.Clear()
            Dim gv As GridView = e.Item.FindControl("gvPrices")
            Dim currentItem As ListViewDataItem = DirectCast(e.Item, ListViewDataItem)
            Dim currentDataKey As DataKey = Me.gvResult.DataKeys(currentItem.DataItemIndex)
            dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings("hotelbedsConnectionString").ConnectionString
            dbSrc.SelectCommandType = SqlDataSourceCommandType.StoredProcedure
            dbSrc.SelectCommand = "GetPriceTest"
            dbSrc.SelectParameters.Add(New Parameter("SearchID", DbType.String, CStr(Request.QueryString("SearchID"))))
            dbSrc.SelectParameters.Add(New Parameter("HotelCode", DbType.String, CStr(currentDataKey.Value)))
            gv.DataSource = dbSrc
            AddHandler gv.RowCommand, AddressOf MarkSelected
            gv.DataBind()
        End If
    End Sub

我在ListView中使用普通的分页控件,如下所示:

<LayoutTemplate>
                    <div id="itemPlaceholderContainer" runat="server" style="">
                        <span runat="server" id="itemPlaceholder" />
                    </div>
                    <div style="">
                        <asp:DataPager ID="DataPager1" runat="server">
                            <Fields>
                                <asp:NumericPagerField ButtonCount="10" CurrentPageLabelCssClass="CurrentPage" NumericButtonCssClass="PageNumbers"
                                    NextPreviousButtonCssClass="PageNumbers" NextPageText=" > " PreviousPageText=" < " />
                            </Fields>
                        </asp:DataPager>
                    </div>
                </LayoutTemplate>

错误是:索引超出范围。必须是非负数且小于集合的大小。 参数名称:index

这是带有嵌套GridView的ListView的完整标记:

  <asp:ListView ID="gvResult" runat="server" DataSourceID="ds_hotels" DataKeyNames="HotelCode">
        <EmptyDataTemplate>
            <span>No data was returned.</span>
        </EmptyDataTemplate>
        <ItemTemplate>
            <div style="width: 96%; float: left;" class="dashed">
                <div style="width: 18%; float: left;">
                    <asp:HyperLink ID="hlHotelInfo" runat="server" Text="Фотографии и информация" NavigateUrl='<%# Eval("HotelCode", "details/{0}") %>'
                        ImageUrl='<%# Eval("HotelCode", "hotelfront.ashx?HotelCode={0}") %>' CssClass="img_hotel"></asp:HyperLink></div>
                <h2 class="title_hotels">
                    <asp:HyperLink ID="Label2" runat="server" Text='<%# ShowHotelName(Eval("HotelCode")) %>'
                        NavigateUrl='<%# Eval("HotelCode", "details/{0}") %>'></asp:HyperLink></h2>
                <p>
                    <asp:Label ID="lblHotelDesc" runat="server" Text='<%# ShowHotelDescr(Eval("HotelCode")) %>' />
                </p>
            </div>
            <asp:GridView runat="server" ID="gvPrices" AutoGenerateColumns="False" GridLines="None"
                Width="100%" RowStyle-HorizontalAlign="Center" DataSourceID="ds_prices" DataKeyNames="ID">
                <AlternatingRowStyle BackColor="#00FF99" />
                <SelectedRowStyle Font-Bold="true" BackColor="BlanchedAlmond" />
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:ImageButton ID="addToBasket" runat="server" ImageUrl="~/img/32px/Add.png" ToolTip="Добавить в корзину"
                                OnCommand="MarkSelected" CommandName="Select" CommandArgument='<%# Eval("ID") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Стоимость">
                        <ItemTemplate>
                            <asp:Label ID="lblPrice" runat="server" Text='<%# ShowMarkUp(Eval("Price", "{0:#0}")) %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="Currency" HeaderText="Валюта" SortExpression="Currency" />
                    <asp:BoundField DataField="AdultCount" HeaderText="Взрослых" SortExpression="AdultCount" />
                    <asp:BoundField DataField="ChildCount" HeaderText="Детей" SortExpression="ChildCount" />
                    <asp:BoundField DataField="RoomCount" HeaderText="Номеров" SortExpression="RoomCount" />
                    <asp:BoundField DataField="RoomTypeName" HeaderText="Тип номера" SortExpression="RoomTypename" />
                    <asp:TemplateField HeaderText="Питание" SortExpression="BoardShortName">
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("BoardShortName") %>' ToolTip='<%# ShowToolTip(Eval("BoardShortName")) %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <RowStyle HorizontalAlign="Center" />
            </asp:GridView>
            <asp:SqlDataSource ID="ds_prices" runat="server" ConnectionString="<%$ ConnectionStrings:hotelbedsConnectionString %>"
                SelectCommand="GetPriceTest" CancelSelectOnNullParameter="False" SelectCommandType="StoredProcedure">
                <SelectParameters>
                    <asp:Parameter Name="SearchID" Type="String" />
                    <asp:Parameter Name="HotelCode" Type="String" />
                </SelectParameters>
            </asp:SqlDataSource>
        </ItemTemplate>
        <LayoutTemplate>
            <div id="itemPlaceholder" runat="server">
            </div>
            <br />
            <asp:DataPager ID="DataPager1" runat="server">
                <Fields>
                    <asp:NumericPagerField ButtonCount="10" CurrentPageLabelCssClass="CurrentPage" NumericButtonCssClass="PageNumbers"
                        NextPreviousButtonCssClass="PageNumbers" NextPageText=" > " PreviousPageText=" < " />
                </Fields>
            </asp:DataPager>
        </LayoutTemplate>
    </asp:ListView>

2 个答案:

答案 0 :(得分:2)

正确的问题是答案的一半,是的...... 我不敢问 - 为什么有超出范围的例外。 asnwer在这里:

 currentDataKey = Me.gvResult.DataKeys(currentItem.DisplayIndex)

@Abide,感谢tryinh帮助我!

答案 1 :(得分:0)

确保在从数据库返回的数据中,数据键中没有带空值的条目导致负索引。并尝试此

Dim currentItem As ListViewDataItem = DirectCast(e.Item, ListViewDataItem)
If currentItem.DataItemIndex < Me.gvResult.Count-1 then
Dim currentDataKey As DataKey = Me.gvResult.DataKeys(currentItem.DataItemIndex)
End if 
Dim HotelCode As String = currentDataKey("HotelCode") ' where the value in quotes would be the name of your datakey.