简体   繁体   中英

Getting a selected value from the drop down list inside a GridView on Update

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

看起来是一个数据绑定错误,您正在尝试访问尚不存在的数据...

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

首先想到的是,您可能应该执行SelectedItem.Value而不是SelectedItem.ToString()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM