I have a GridView containing records from a table which can be deleted or updated. If you want to edit a row, it should display the update and cancel buttons so that you can keep or cancel the current edit (I hide update and cancel as default). I am using the following asp for the button column of the GridView:
<asp:TemplateField visible ="true" >
<HeaderTemplate>
<div id = "header">Maintain</div>
</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="btnDelete" Text="Delete" Runat="Server" CommandName="Delete" Visible="true" CommandArgument='<%#Eval("UNIQUEID")%>'/>
<asp:Button ID="btnEdit" Text="Edit" Runat="Server" CommandName="Edit" Visible="true" CommandArgument='<%#Eval("UNIQUEID")%>'/>
<asp:Button ID="btnCancel" Text="Cancel" Runat="Server" CommandName="Cancel" Visible="false" CommandArgument='<%#Eval("UNIQUEID")%>'/>
<asp:Button ID="btnUpdate" Text="Update" Runat="Server" CommandName="Update" Visible="false" CommandArgument='<%#Eval("UNIQUEID")%>'/>
</ItemTemplate>
</asp:TemplateField>
I use the following code to handle the command that has been pressed:
protected void grdResults_RowCommand(object sender, GridViewCommandEventArgs e)
{
int pk;
if (e.CommandName == "Edit")
{
int index = 0;
foreach (result r in allSearchResults) //get the row index with the grid
{
if (r.UniqueID == Convert.ToInt32(e.CommandArgument))
break;
index++;
}
((Button)(grdResults.Rows[index].FindControl("btnUpdate"))).Visible = true;
((Button)(grdResults.Rows[index].FindControl("btnCancel"))).Visible = true;
}
if (e.CommandName == "Delete")
{
_presenter.modifySearchResults(Convert.ToInt32(e.CommandArgument)); //delete the item from the search results
}
if (e.CommandName == "Update")
{
//TODO update the search results with the edited text
}
if (e.CommandName == "Cancel")
{
//TODO cancel the current edit
}
}
For some reason however, when I click edit, it does not show the update button. When I step through the code it does find the btnUpdate control and changes its visibility correctly but does not show on the screen.
Probably it is in the wrong place in ASP.NET lifecycle. Try moving showing/hiding buttons to PreRender