asma
asma

Reputation: 2825

GridView Paging Issue

I am using a gridview control and performing Paging and Sorting manually. Here is the method of Paging:

protected void gdvMainList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gdvMainList.PageIndex = e.NewPageIndex;
        gdvMainList.DataSource = dtConsentReleaseList;
        gdvMainList.DataBind();
    }

I have a static datatable having a column Id:

dtConsentReleaseList.Columns.Add("Id");
            dtConsentReleaseList.Columns.Add("StartDate");
            dtConsentReleaseList.Columns.Add("EndDate");
            dtConsentReleaseList.Columns.Add("Contact");

I am assigning datakeynames "Id" in my GridView. And I also have a print button in each row. When I click that button, this code gets executed:

else if (e.CommandName == "New")
        {                
            int selectedIndex = Convert.ToInt32(e.CommandArgument);
            int consentReleaseId = Convert.ToInt32(gdvMainList.DataKeys[selectedIndex].Value);
            string openReportScript = Utility.OpenReport(ResolveClientUrl("~/Reports/Consumer/ConsentReleaseReport.aspx?Id=" + consentReleaseId + "&ReportTitle=ConsentForRelease"));
            ScriptManager.RegisterClientScriptBlock(upConsentRelease, upConsentRelease.GetType(), "Pop up", openReportScript, true);
        }

but when I change the page and clicks print button, an exception occurs on this line :

int consentReleaseId = Convert.ToInt32(gdvMainList.DataKeys[selectedIndex].Value);

Exception is:

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

I guess I am doing something wrong in Paging method.

Any help please?

Upvotes: 3

Views: 2098

Answers (3)

Josh M.
Josh M.

Reputation: 27773

You are trying to get a value out of an array based on an arbitrary ID instead of the actual index. But you don't need to do that at all. You don't need to store your ID in the DataKeys and you don't need to access anything using the index of the item. Just pull your ID out from the CommandArgument.

<asp:ImageButton CommandName="New" CommandArgument='<%# Eval("Id") %>' ID="ibtnPrint" runat="server" ImageUrl="~/App_Themes/Default/images/print.png" />

And then in code-behind:

int consentReleaseId = int.Parse(e.CommandArgument);

Upvotes: 1

JonH
JonH

Reputation: 33141

Set the datakeyname right before you set the datasource and bind the gridview.

In addition,

string[] dk = new string[1] {"MyID"};
myGridView.DataKeyNames = dk;
myGridView.DataSource = ds;
myGridView.DataBind();

Upvotes: 0

Kamyar
Kamyar

Reputation: 18797

My guess is that you bind the gridview in code-behind (possibly page_load event) and it doesn't hold the values on postback.

Also, try to pass the Id as CommandArgument. As far as I can tell, if you have access to Id of the selected record, you don't need grid's row index at all. (GridView passes row's index as CommandArgument by default)

Upvotes: 0

Related Questions