Cookie Monster
Cookie Monster

Reputation: 19

C# Gridview Datakeys not filled in live environment

I have a C# 4.8 Gridview with Datakeys that works just fine in localhost environment, but not in production (!)

A RowCommand event looks for a Datakey value :


        protected void GridView_Contracts_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (!Page.IsCallback) {
                if (e.CommandName == "DETAILS")
                {
                    int RowIndex = Convert.ToInt32(e.CommandArgument);

                    // following instruction works in localhost, but returns "Index was out of range" on live environment, because GridView_Contracts.DataKeys.Count=0
                    string sIdContract = GridView_Contracts.DataKeys[RowIndex]["ID_CONTRACT"].ToString();
                    SES.SetIdContract(sIdContract);
                    Response.Redirect("ContractDetails.aspx", false);
                }
            }
        }
                    

But, once published on the live IIS server, this RowCommand event creates the following error :

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

Other websites are hosted on the same IIS and use the same kind of Gridviews & Datakeys the same way successfully, but they're written in VB.NET.

I haven't tweaked the Gridview params in a weird way, or have any special code messing with it through custom events or anything.

Tried publishing the app on another server as a troubleshoot, unsuccessfully.

Debugging shows that on the live server : GridView_Contracts.DataKeys.Count=0 vs GridView_Contracts.DataKeys.Count=30 on localhost.

The only thing I can think of would be something related to zero-based VS 1-based server params, as we have some other VB apps runnning on the same IIS, but to be honest I'm quite puzzled. Would you guys have a clue ?

Thanks a lot !

Upvotes: 0

Views: 33

Answers (1)

Cookie Monster
Cookie Monster

Reputation: 19

I have removed the Gridview databind instruction from the Page_Load() event and only refresh it when required. It solved the problem. I can see why refreshing the values might mess up with the DataKeys, but I still wonder why it works in localhost !

// don't call this sub in the Page_Load() event
    
private void RefreshGridview()
{
    this.SqlDataSource_Contracts.SelectCommand = GetGridviewSql();
    this.GridView_Contracts.DataBind();
    Label_Gridview.Text = GridView_Contracts.Rows.Count + " contracts in the database";
}        

Upvotes: 0

Related Questions