0
votes

I have an ASP.NET gridview component which is being filled up with data from a database. I have also added a template field in the gridview which contains a DropDownList component. I have also created a separate button (not a gridview field). When this button is clicked, the program goes through all the GridView rows and checks the DropDownList of each row and when a DropDownList with a selected value other than 0 is found, it puts the details of that particular row in a session to be sent to another page. The code is as follows:

protected void CheckoutButton_Click(object sender, EventArgs e)
{
    int n = 0;

    foreach (GridViewRow row in GridView1.Rows)
    {
        if (((DropDownList)row.FindControl("DropDownList1")).SelectedItem.Value == "0")
        {
        }
        else
        {
            n++;
            Session["ProductList" + n] = row.Cells[0].Text;
            Session["QuantityList" + n] = row.Cells[5].Text;
            Session["NumberofResults" + n] = n;
        }
    }
}

The problem I am having is that when the 'Checkout' button is clicked, the value being read from the DropDownList is not the value that the user has selected, but its default value. Basically the value of the dropdownlist is being changed back to the default before the code in the CheckoutButton_Click method is executed.

Any ideas please?

1
Is your code that binds the grid in your Page_Load event? Sounds like the grid is re-binding on PostBack.Kev Ritchie
Yes I am binding the data from the database to the gridview in the Page_Load event. Any suggestions then? Thanks!lvella
Could you post a code example of your Page_Load event, thanks.Kev Ritchie
I enclosed the code in the Page_Load event within an if(!IsPostBack) statement and it works. Thanks a lot for your help! :)lvella
Excellent! :) For completeness I have added the answer below so that it can be marked as the answer for other SO users.Kev Ritchie

1 Answers

0
votes

You need to wrap you code in the Page_Load event with if(!IsPostBack) to make sure the value selected is retained.