0

I'm binding data to GridView nested in ListView via ItemDataBound and when I'm paging ListView it's loosing datakey value. Here is DataBound event:

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

I'm using normal paging control in ListView like this one:

<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>

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

Here is full markup of ListView with nested GridView:

  <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>
andrey.shedko
  • 3,128
  • 10
  • 61
  • 121

2 Answers2

2

Correct question is the half of the answer, yeah... I shoud rather ask - why there is out of range exception. The asnwer is here:

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

@Abide, thanks for tryinh to help me!

andrey.shedko
  • 3,128
  • 10
  • 61
  • 121
0

Make sure that in the data being brought back from the database there is no entry with a null value in your datakey causing a negative index.And try this

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.
abidmix
  • 1,748
  • 1
  • 16
  • 26
  • In your immediate window what is the value of ? Me.gvResult.DataKeys.Check if you are getting the datakey collection at all.Can you post how you declared your datakey in your mark up. – abidmix Nov 11 '13 at 10:08
  • All values getting and passing to stored procedure, but when I' changing page there exception about out of range. – andrey.shedko Nov 11 '13 at 10:18
  • Put a breakpoint on your itemDataBound event .Try to go to the next page and tell me what is the value of ?Me.gvResult.DataKeys when that breakpoint gets hit or whats the value of your index(currentItem.DataItemIndex) at that particular point. – abidmix Nov 11 '13 at 10:39
  • There is 10 records in ListView, so indexes from 0 to 9. In immediate window I found that exception thrown when index is 10. – andrey.shedko Nov 11 '13 at 10:48
  • Great! then do a check for that in your code.See updated answer – abidmix Nov 11 '13 at 11:09