Eric Mbiada Eric Mbiada -4 years ago 47
ASP.NET (C#) Question

Error when I tried to hide the delete button on the Gridview

I have the error below when I tried to hide the delete button from the gridview when the user is not admin.
"Additional information: Object reference not set to an instance of an object"

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ClinicalFollowUpID"
OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
AllowPaging="True" OnPageIndexChanging="OnPaging" PageSize="5"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting">
<Columns>
<asp:GridView ID="GridView1" runat="server AutoGenerateColumns="False" DataKeyNames="ClinicalFollowUpID"
OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting">
<Columns>
<asp:TemplateField HeaderText="ID" Visible="false">
<ItemTemplate >
<asp:Label ID="lblClinicalFollowUpID" runat="server" Text='<%# Eval("ClinicalFollowUpID") %>' >
</asp:Label>
</ItemTemplate>

</asp:TemplateField>
<asp:TemplateField HeaderText="MBID">
<ItemTemplate >
<asp:Label ID="lblMBID" runat="server" Text='<%# Eval("MBID") %>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150" HeaderText="Click to Edit">
<ItemStyle Width="150px"></ItemStyle>
</asp:CommandField>
</Columns>




C# Code

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
lbltype.Text = Session["Type"].ToString();
if (e.Row.RowType == DataControlRowType.DataRow)
{

if (lbltype.Text != "admin")
{

LinkButton lnkedit = (LinkButton)GridView1.FindControl("lnkedit");
lnkedit.Visible = false;
}
}
}

Answer Source

You won't be able to access the link button using FindControl unless you define the template manually after turning off the AutoGenerateEditButton property of the grid view.

Try the following to find the edit link button and hide it (assuming the last column corresponds to the command field):

if (e.Row.RowType == DataControlRowType.DataRow)
  {
     if (lbltype.Text != "admin")
       {
         LinkButton deleteLink = (LinkButton)e.Row.Cells[e.Row.Cells.Count - 1].Controls[2];
         if(deleteLink != null && deleteLink.CommandName.Equals("Delete"))
           {
              deleteLink.Visible = false;
           }
       }
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download