Barnabeck Barnabeck - 1 year ago 43
ASP.NET (C#) Question

RowDataBound not acting the way I expect

I have a Gridview with an ImageButton that should become visible for the selected row only. I'm doing this in the OnRowDataBound event, but it doesn't work.

protected void OnRowDataBoundMS(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
// some working code that handles the edit mode
else if (Gridview1.SelectedValue != null)
ImageButton ImgBut1 = e.Row.FindControl("ButtonUp") as ImageButton;
ImgBut1.Visible = true;

My gridview looks like this:

<asp:GridView runat="server"
<asp:templatefield HeaderText="Order" ItemStyle-HorizontalAlign="center">
<asp:ImageButton ID="ButtonUp" runat="server" OnClick ="OrderUp" ImageUrl="img/up.png" Visible="false"/>

I spent the last 3 hours on this and I start to freak out. Any hints on this? Martin

Answer Source

The other alternative is to use the SelectedIndexChanged event if you are using the Select command option:

protected void OnSelectedIndexChangedMS(object sender, EventArgs e)
    foreach (GridViewRow row in GridView1.Rows)
        Control ctl = row.FindControl("ButtonUp");
        ctl.Visible = (row.RowState & DataControlRowState.Selected) != 0;

Something like that; RowDataBound may fire before the selected index gets updated (not sure about that...).