开发者

Having Problems getting a Grid View to select a row in C#

开发者 https://www.devze.com 2023-03-06 15:07 出处:网络
I\'ve been working on this problem for a few days now. Background: I have a shopping cart set up and it is stored in the session. I am pulling it out of session and binding it to a Grid View. I want

I've been working on this problem for a few days now.

Background: I have a shopping cart set up and it is stored in the session. I am pulling it out of session and binding it to a Grid View. I want users to be able to change the quantity of an item. I am running into several problems and this one is just not ironing itself out.

I have a button in each row with the Command Name "Select". When you 开发者_如何转开发click that button it brings up a Modal Pop Up window with a text box.

However when I click the button the SelectedValue is -1 and it throws an Out of Range exception.

It should be the ProductId of the item. the DataKey Name is the Product ID and when I show the product ID in the grid view it comes up as the correct non -1 ID.

 protected void btnChange_Click(object sender, EventArgs e)
{
    Dictionary<int, ShoppingCartItem> cart = (Dictionary<int, ShoppingCartItem>)Session["Cart"];


    cart[(int)gvCart0.SelectedValue].Quantity = int.Parse(tbQuantity.Text);
    gvCart0.DataBind();
}


Note::please change the CommandName of your button to "selectCart"

Set the command argument property for your button :

.aspx

CommandArgument='<%#((GridViewRow)Container).RowIndex%>'

.cs

 protected void gvCart0_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            int index = Convert.ToInt32(e.CommandArgument);
            if (e.CommandName == "selectCart")
            {

                Dictionary<int, ShoppingCartItem> cart = (Dictionary<int, ShoppingCartItem>)Session["Cart"];
                cart[index].Quantity = int.Parse(tbQuantity.Text);

            }

            gvCart0.DataBind();

        }

        catch (Exception ee)
        {
            string message = ee.Message;
        }
    }


For RowEditing you have to do something like this on the RowEditing event to set the EditIndex,

protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
{
    grid.EditIndex = e.NewEditIndex;
}

You may need to do the same with the OnSelectedIndexChanging event.


At first on ItemCommand get the ProductId and store it in a View-State and after that on the ButtonClick Event do the corresponding thing you want to do by getting the ProductId from the View-State and don't forget to set the Data-Source to Grid-View as you are modifying the collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消