开发者

dynamically hiding linkbuttons in a gridview

Here is my template field with 2linkbuttons in a gridview. How do I hide one of the lnkbuttons depending on the user selection

       <asp:TemplateField HeaderText="Action">
       <ItemTemplate>
       <table>
       <tr&开发者_StackOverflowgt;

       <td align="center">
       <asp:LinkButton ID="LinkButton1" runat="server" CommandName= "Publish" CommandArgument="<%# Container.DataItemIndex %>"></asp:LinkButton>
       </td>

       <<td align="center">
        <asp:LinkButton ID="LinkButton2" runat="server"   CommandName= "Block" HeaderText="Block" CommandArgument="<%# Container.DataItemIndex %>">Block</asp:LinkButton>
       </td>

       </tr>
       </table>
       </ItemTemplate>

       </asp:TemplateField>       


protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {


   if(Status=="Posted")
   {
            LinkButton lbtn2 = (LinkButton)e.Row.FindControl("LinkButton2");
            lbtn2.Visible = false;
    }
   if(Status=="Publish")
       {
                LinkButton lbtn1 = (LinkButton)e.Row.FindControl("LinkButton1");
                lbtn1.Visible = false;
        }
    }

I am doing this using 2 linkbuttons in the template field. Here if the Status == Posted, then hide LinkButton2. If ItemType == Published, then hide LinkButton1.

I don't mind using only Linkbutton and set the commandName and commandArgument in aspx.cs`

I am getting an error at...

LinkButton lbtn2 = (LinkButton)e.Row.FindControl("LinkButton2");
lbtn2.Visible = false;

Error: Object reference not set to an instance pointing to lnbt2.Visible = false;

Any clues, Thanks Sun


Check to be sure that the row in question is a data row, not a header, etc. The issue is probably because the current row is a header or footer, so it doesn't contain your controls and throws an exception.

protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        if(Status=="Posted")
        {
            LinkButton lbtn2 = (LinkButton)e.Row.FindControl("LinkButton2");
            lbtn2.Visible = false;
        }
        if(Status=="Publish")
        {
            LinkButton lbtn1 = (LinkButton)e.Row.FindControl("LinkButton1");
            lbtn1.Visible = false;
        }
    }
}


I know this is old but I was looking for the same thing; I was able to do it this way also and posting just for reference:

This is in a listview but should be same for gridview:

<asp:LinkButton ID="btnForms" runat="server" Text='MyButton' CommandName="MyCommandName"
Style='<%#GetHiddenTag(Eval("Status").ToString())%>'  CommandArgument='<%#Eval("Status")%>' OnClick="MyOnClickCodeBehind" />

Codebehind:

    public string GetHiddenTag(string Status)
    {
        if (Status.ToLower() == "completed")
            return "visibility:hidden;";

        return "visibility:visible;";
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜