2

Here is my aspx code:

<EditItemTemplate>
   <asp:DropDownList ID="ddlTotalColumn" runat="server">
       <asp:ListItem Value="">Select value</asp:ListItem>
       <asp:ListItem Value="0">1</asp:ListItem>
       <asp:ListItem Value="1">2</asp:ListItem>
   </asp:DropDownList>
</EditItemTemplate>

My aspx.cs code:

protected void gvTest_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow selected_row = gvTest.Rows[e.RowIndex];

    var total_column_drop_down_list = (DropDownList)selected_row.FindControl("ddlTotalColumn");

    int column_string = Convert.ToInt32(total_column_drop_down_list.SelectedItem.Value);

    gvTest.EditIndex = -1;
    ...
}

At this line: int column_string = Convert.ToInt32(total_column_drop_down_list.SelectedItem.Value); I have an error: "Input string was in incorrect format" because "total_column_drop_down_list.SelectedItem.Value" will return empty string ("").

So is there any bright idea?

Anh Hoang
  • 2,242
  • 3
  • 22
  • 23

1 Answers1

4

It sounds like you have made the classic mistake of not putting your databinding code inside a if (!Page.IsPostBack) block. Thus, your GridView re-binds, and you get default values in your RowUpdating event (rather than what you selected).

Wherever you are binding your GridView, in Page_Load for instance, you need to do this:

if (!Page.IsPostBack)
{
    BindGrid();
}

Where "BindGrid()" is whatever code you call to databind your GridView.


On a slightly unrelated note, you can actually use the GridViewUpdateEventArgs parameter that's passed to that method to grab the updated values (rather than using FindControl to get the DropDownList, and then getting the values).

Josh Darnell
  • 11,304
  • 9
  • 38
  • 66
  • Do you have a code snippet to do that? I am trying to solve that exact issue. – htm11h Nov 18 '14 at 14:52
  • @htm11h Code snippet to do what? Get the values from the GridViewUpdateEventArgs object? – Josh Darnell Nov 18 '14 at 15:38
  • Check out the docs, @htm11h. There's a good example at the bottom of using the .NewValues collection to get what you need: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewupdateeventargs(v=vs.110).aspx – Josh Darnell Nov 18 '14 at 15:45