禁用/隐藏GridView特定行内的控件

时间:2014-06-27 04:48:12

标签: c# asp.net gridview

我有以下代码在asp.net和gridview中创建gridview我有一个删除按钮。下面的代码工作正常,并显示所有行中的删除。 我想隐藏/禁用第一行中的“删除”按钮。有人可以建议代码部分吗?

<asp:gridview ID="Gridview1" runat="server" 
  ShowFooter="true" AutoGenerateColumns="false">
     <Columns>
            <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                <asp:TemplateField HeaderText="Cat">
                <ItemTemplate>
                    <asp:TextBox ID="TextBoxCat" runat="server" Enabled="false"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
              <asp:TemplateField HeaderText="Delete" >
                            <ItemTemplate>
                                <asp:LinkButton ID="DeleteItemsGridRowButton" runat="server">Delete</asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
            </Columns>
        </asp:gridview>

2 个答案:

答案 0 :(得分:1)

试试这个:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if(GridView1.Rows.Count>0)
   {
    //GridView1.Rows[0].Visible = false;
       LinkButton DeleteItemsGridRowButton=   (LinkButton) GridView1.Rows[0].FindControl("DeleteItemsGridRowButton");
       if(DeleteItemsGridRowButton!=null)
       {
        DeleteItemsGridRowButton.Visible=false
       }
   }
}

答案 1 :(得分:1)

您可以使用GridView.RowDataBound Event活动。

然后使用 FindControl 方法找到 LinkBut​​ton

enter image description here

public class Animal
{
    public int RowNumber { get; set; }
    public string Name { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Gridview1.DataSource = new List<Animal>
        {
            new Animal {RowNumber = 1, Name = "One"},
            new Animal {RowNumber = 2, Name = "Two"},
            new Animal {RowNumber = 3, Name = "Three"},
            new Animal {RowNumber = 4, Name = "Four"},
        };
        Gridview1.DataBind();
    }
}

private int _counter;

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (_counter == 0)
        {
            var linkButton = e.Row.FindControl("DeleteItemsGridRowButton") 
                as LinkButton;
            linkButton.Visible = false;
            _counter++;
        }
    }

}