Conditionally hide CommandField or ButtonField in Gridview

disable commandfield gridview
how to disable button in gridview based on condition in asp.net c#
how to hide and show gridview in asp net
hide update button in gridview asp net c#
how to hide gridview column in asp net using c#
how to disable grid view button in c#
how to disable linkbutton in gridview rowcommand
gridview row visible false in c#

I have a GridView displaying person records. I want to conditionally show a CommandField or ButtonField based on some property of the underlying record. The idea is to only allow a command to be performed on specific people.

What is the best way to do this? I'd prefer a declarative solution to a procedural one.

First, convert your ButtonField or CommandField to a TemplateField, then bind the Visible property of the button to a method that implements the business logic:

<asp:GridView runat="server" ID="GV1" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Age" HeaderText="Age" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button runat="server" Text="Reject" 
                Visible='<%# IsOverAgeLimit((Decimal)Eval("Age")) %>' 
                CommandName="Select"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Then, in the code behind, add in the method:

protected Boolean IsOverAgeLimit(Decimal Age) {
    return Age > 35M;
}

The advantage here is you can test the IsOverAgeLimit method fairly easily.

Gridview, hi, In Gridview, I have "EDIT" commandfield for each row. but sometimes I want to hide the "EDIT" Commandfield from codebehind. Is it possible  Conditionally Hide or disable Gridview commandfield buttonfield in asp.net. I'll use field such as Select,ShowEditButton and controls in TemplateField for this demo. Northwind Databse is used to populate GridView. Enable selection from smart tag in design mode to show SelectButton Hyperlink in Gridview.

it could be done when the RowDataBound event fires

  protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  {
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      // Hide the edit button when some condition is true
      // for example, the row contains a certain property
      if (someCondition) 
      {
          Button btnEdit = (Button)e.Row.FindControl("btnEdit");

          btnEdit.Visible = false;
      }
    }   
  }

Here's a demo page

markup

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DropDownDemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>GridView OnRowDataBound Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField HeaderText="Name" DataField="name" />
                <asp:BoundField HeaderText="Age" DataField="age" />
                <asp:TemplateField>
                    <ItemTemplate>                
                        <asp:Button ID="BtnEdit" runat="server" Text="Edit" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>
</body>
</html>

Code Behind

using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;

namespace GridViewDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GridView1.DataSource = GetCustomers();
            GridView1.DataBind();
        }

        protected override void OnInit(EventArgs e)
        {
            GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
            base.OnInit(e);
        }

        void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow) return;

            int age;
            if (int.TryParse(e.Row.Cells[1].Text, out age))
                if (age == 30)
                {
                    Button btnEdit = (Button) e.Row.FindControl("btnEdit");
                    btnEdit.Visible = false;
                }
        }

        private static List<Customer> GetCustomers()
        {
            List<Customer> results = new List<Customer>();

            results.Add(new Customer("Steve", 30));
            results.Add(new Customer("Brian", 40));
            results.Add(new Customer("Dave", 50));
            results.Add(new Customer("Bill", 25));
            results.Add(new Customer("Rich", 22));
            results.Add(new Customer("Bert", 30));

            return results;
        }
    }

    public class Customer
    {
        public string Name {get;set;}
        public int Age { get; set; }

        public Customer(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }
}

In the demo, the Edit Button is not Visible (the HTML markup is not sent to the client) in those rows where the Customer's age is 30.

Hide Disable CommandField ButtonField In GridView Asp.Net, In this example i'm going to explain how to Conditionally Hide Or Disable GridView CommandField Or ButtonField Programmatically In Asp.Net Using C# And  Hide Disable CommandField ButtonField In GridView Asp.Net Posted by Manoj Ram on 3:06 AM with No comments so far In this example i'm going to explain how to Conditionally Hide Or Disable GridView CommandField Or ButtonField Programmatically In Asp.Net Using C# And VB

Allow me to share my approach for what it's worth. For me converting the commandfield to a templatefield control is not an option, as the commandfield comes with built-in functionality that I would otherwise have to create myself, for example the fact that it changes to "Update Cancel" when Edit is clicked, and that when Edit is clicked, all the cells in the row which are labels become textboxes, etc.

In my approach, you can leave the commandfield as is, then you can hide it as needed via code behind. In this example, I am hiding it if the field "Scenario" of the grid shows the text "Actual" for the relevant row of the RowDataBound event.

protected void gridDetail_RowDataBound(object sender, GridViewRowEventArgs e)
    {   
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (((Label)e.Row.FindControl("lblScenario")).Text == "Actual")
            {
                LinkButton cmdField= (LinkButton)e.Row.Cells[0].Controls[0];
                cmdField.Visible = false;
            }
    }}

Conditionally hide CommandField or ButtonField in Gridview, I have a GridView displaying person records. I want to conditionally show a CommandField or ButtonField based on some property of the underlying record. You can hide a CommandField or ButtonField based on the position (index) in the GridView. For example, if your CommandField is in the first position (index = 0), you can hide it adding the following code in the event RowDataBound of the GridView:

Hide the Entire GridView Column

If you want to remove the column completely (i.e. not just the button) from the table then use a suitable event handler, e.g. for the OnDataBound event, and then hide the appropriate column on the target GridView. Pick an event that will only fire once for this control, i.e. not OnRowDataBound.

aspx:
<asp:GridView ID="grdUsers" runat="server" DataSourceID="dsProjectUsers" OnDataBound="grdUsers_DataBound">
    <Columns>
        <asp:TemplateField HeaderText="Admin Actions">
            <ItemTemplate><asp:Button ID="btnEdit" runat="server" text="Edit" /></ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="FirstName" HeaderText="First Name" />
        <asp:BoundField DataField="LastName" HeaderText="Last Name" />
        <asp:BoundField DataField="Telephone" HeaderText="Telephone" />
    </Columns>
</asp:GridView>
aspx.cs:
protected void grdUsers_DataBound(object sender, EventArgs e)
{
    try
    {
        // in this case hiding the first col if not admin
        if (!User.IsInRole(Constants.Role_Name_Admin))
            grdUsers.Columns[0].Visible = false;
    }
    catch (Exception ex)
    {
        // deal with ex
    }
}

[Solved] How to show and hide a button field in gridview if a row , Data Item of Field Value can be obtained in one by one during rowdatabound event.Don't be confused to run a iteration loop to get each values  Make asp buttonfield visible at runtime. Conditionally hide CommandField or ButtonField in Gridview. Conditionally hide CommandField or ButtonField in

Convert the CommandField to a TemplateField and set the visible property of the button based on the value of the field (true/false)

<asp:Button ID="btnSelect" 
runat="server" Text="Select" 
Visible='<%# DataBinder.Eval(Container.DataItem,"IsLeaf") %>'/>

Conditionally Hide Commandfield or Buttonfield in Gridview, Conditionally Hide or disable Gridview commandfield buttonfield in asp.net. I'll use field such as Select,ShowEditButton and controls in  Within a GridView, I have a command field set as such < asp:CommandField ShowSelectButton =" false" ButtonType =" Button" SelectText =" Select" / > When the grid fist displays the select button is hidden on all rows. That works fine. In the click event in another button, I want to set ShowSelectButton="true" so that the select button shows up on all rows.

Show Hide Button in GridView based on condition in ASP.Net, Conditionally Hide Commandfield or Buttonfield in Gridview. ASP Code: <asp:​GridView runat="server" ID="GV1"  Conditionally Hide CommandField in Grid View; Get Max and Min value of DataTable; Conditionally Hide Commandfield or Buttonfield in Gridview; Check/UnCheck al Checkboxes in Grid View; RSS pubDate in .Net c#; How to delay the code execution process in C#; How to enable/disable jquery autocomplete; Adding a value from the querystring to a

How to access the CommandField in Gridview from code behind?, I have a GridView displaying person records. I want to conditionally show a CommandField or ButtonField based on some property of the underlying record. Conditionally hide CommandField or ButtonField in Gridview (6) Hide the Entire GridView Column If you want to remove the column completely (i.e. not just the button) from the table then use a suitable event handler, e.g. for the OnDataBound event, and then hide the appropriate column on the target GridView .

The following HTML Markup consists of an ASP.Net GridView consisting of two BoundField columns and one TemplateField column populated 

Comments
  • could you elaborate on what you mean by a declarative solution?
  • @RussCam I think he means "as little C# as possible", using the markup syntax instead of the code-behind.
  • Exactly answer I was looking for. Nice, thanks. Don't you just love those not-so-well-documented GridView features? :-)
  • @levi I edited the answer slightly to include the command name (for a select command) within the proposed button.
  • @Marcel will it effect the performance as the button's visible is calling the server side event every time.if yes please suggest an alternative way
  • @clarifier Well, it's calling the code behind method every time. This in itself is inexpensive. However you should pay attention to the implementation of the method. If it is expensive, this could easily sum up to a large cost. A simple comparison should be no problem. To be sure, use a profiling tool.
  • I almost gave up and just convert my commandfield to a templatefield but I know it can be done so I keep on searching for it. I think this should be the correct answer. (Although I'm still not sure what the asker meant about the declarative answer.)
  • yes, I prefer this approach. Without assuming which control is which, you can also loop through and check CommandName
  • I also agree that this answer is the most appropriate to the formulated question. While changing the commandfield to a templatefield does work (and imo is better in most cases) - the question is how to specifically hide a commandfield.
  • this is exactly what I was looking for