当我尝试在用户不是管理员时隐藏gridview中的删除按钮时,我有以下错误。 "其他信息:未将对象引用设置为对象实例 "
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#代码
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;
}
}
}
答案 0 :(得分:1)
除非您在关闭网格视图的 AutoGenerateEditButton 属性后手动定义模板,否则您将无法使用FindControl访问链接按钮。
尝试以下操作以查找编辑链接按钮并将其隐藏(假设最后一列对应于命令字段):
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;
}
}
}
答案 1 :(得分:0)
试试这个
Button btnEdit = (Button)e.Row.FindControl("Link");
btnEdit.Visible = false;
或
if (e.Row.RowType == DataControlRowType.DataRow )
{
var editBtn= e.Row.Cells[3].Controls[2] as Button;
editBtn.Visible = false;
}