Reputation: 33
I am trying to hide (or show) an EDIT commandfield button on my GridView. To do this, I am following the example here (Conditionally hide CommandField or ButtonField in Gridview) which worked great. I converted the field to a templatefield, named the button, and sure enough it works (hides/shows as expected). YAY!
One problem though. When I click on the EDIT button, I do not go into edit mode, and I get an error actually. The error is, "Object Reference not set to an instance of the object". This is on the line that reads, "btnEdit.Visible = false;"
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Hide the edit button when some condition is true
// for example, the row contains a certain property
if (CanEdit == false)
{
System.Web.UI.WebControls.LinkButton btnEdit = (System.Web.UI.WebControls.LinkButton)e.Row.FindControl("btnEdit");
btnEdit.Visible = false;
}
else
{
System.Web.UI.WebControls.LinkButton btnEdit = (System.Web.UI.WebControls.LinkButton)e.Row.FindControl("btnEdit");
btnEdit.Visible = true;
}
}
I did have another seperate technique to hide the EDIT button which was to use .Controls.Clear() when a condition was met in the RowDataBound event. That complete line is, "e.Row.Cells[e.Row.Cells.Count - 1].Controls.Clear();" The problem is, when I click on the EDIT button an dgo into EDIT mode, the UPDATE and CANCEL button's are not there. I asusme they were cleared in the previous command.
if (CanEdit == false)
{
//disble row editing
//e.Row.Cells[e.Row.Cells.Count - 1].Controls.Clear();
}
So my question can be one or the other. How can I convert the field to a template field, make the edit button visible and go into edit mode when the button is clicked. OR, how can I use hte .Controls.Clear() method, but clear only the edit button?
Thank you so much!
Upvotes: 0
Views: 1456