tags:

views:

1742

answers:

3

I have a GridView, each row has Edit button. After it's clicked, one of the columns turns into a drop down list where users can select value. Edit button becomes Update - so very simple usual scenario.

Now, I don't seem to be able to grab the selected drop down list after Update is clicked. Here is my code:

    protected void gv_UpdateRow(string arg)
{
    int currentIndex = gv.EditIndex;
    gv.EditIndex = -1;

    GridViewRow currentRow = gv.Rows[currentIndex];

    try
    {
      string value2 = ((DropDownList)currentRow.FindControl("ddlValueTwo")).SelectedItem.ToString();

    }
    catch
    {
        Response.Write("error");
    }


    BindGridView(); 
}

So basically, the program execution always ends up at the catch statement. I have checked and drop down list is found, the exception is thrown when selected item is not found.

What gives?

I use c# asp.net 2.0 web forms

A: 

First thought is that you should probably do SelectedItem.Value rather than SelectedItem.ToString().

Harv
Or just ((DropDownList)currentRow.FindControl("ddlValueTwo")).SelectedValue;
Cory Larson
Too true. Either one would be better than SelectedItem.ToString(), but I'm wondering if that's really the issue since he says the control is found, but selecteditem is null or not an object.
Harv
FYI: I need both the selected item and selected value.
gnomixa
Hm, well if SelectedItem is null or not an object then could you be resetting the form on postback somewhere? Ie do you have a Page_Load method that is firing on postback?
Harv
+1  A: 

Looks like a databinding error, you are trying yo access data that is not present yet...

Colin
A: 

got it!

it was the IsPostback, I was missing it, so the gridview was being rebound every page load, and since the drop down list is inside the grid, the data was lost.

However, one thing I forgot to mention here is that all this code sits inside the user control (ascx file) and IsPostBack property applies to the page not the control, which is useless in my case. For example, in my circumstances I add the control manually, so IsPostback will ALWAYS be true, so to avoid this problem I had to implement a session based solution. Hope this helps someone.

There also usercontrol.IsPostBack property but it didn't perform as expected, perhaps they got it right for 3.0

gnomixa