Can't select another row in ASP.NET GridView (first selection works) because __doPostBack script is missing

StackOverflow https://stackoverflow.com/questions/23543171

  •  18-07-2023
  •  | 
  •  

Question

I have a problem with a GridView in an ASP.NET web forms application. Basically what happens is that I have code in place to select a row by clicking on it, which works only the first click. When clicking on other rows, nothing happens and in the browser console I get __doPostBack is undefined errors.

The code to allow row selection is mostly based on handling the OnRowDataBound event, which looks like this in my case:

protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackEventReference(gvUsers, "Select$" + e.Row.RowIndex);
    }
}

And the following is what I do in the selection changing event handler:

protected void gvUsers_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
    GridViewRow row = gvUsers.Rows[e.NewSelectedIndex];
    row.CssClass = "selectedUser";
}

Nothing special really. This works for lots of people. But when I inspect the HTML that is returned by the server after the handling of this event, indeed the __doPostBack script is missing, as well as the two hidden inputs it uses.

Was it helpful?

Solution

I guess I won't know the reason why __doPostBack is not defined after changing row selection any time soon, but the workaround for now is to 'force' the generation of this function in a standard fashion (lots of people have had various underlying reasons to do this):

protected void Page_Load(object sender, EventArgs e)
{
    Page.ClientScript.GetPostBackEventReference(gvUsers, "");

    //other logic
}

It seems like certain rare circumstances trigger weird bugs in the ASP.NET framework concerning the __doPostBack function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top