Barnabeck Barnabeck - 3 months ago 8
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"
ID="Gridview1"
DataSourceID="Milestones"
DataKeyNames="ID"
AutoGenerateColumns="false"
OnRowEditing="OnRowEditing"
OnRowDataBound="OnRowDataBoundMS"
OnSelectedIndexChanged="OnSelectedIndexChangedMS">
...
<asp:templatefield HeaderText="Order" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:ImageButton ID="ButtonUp" runat="server" OnClick ="OrderUp" ImageUrl="img/up.png" Visible="false"/>
</ItemTemplate>
</asp:templatefield>


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

Answer

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...).