Dynamically set control visibility inside ItemTemplate’s of GridView using Bind Expression

GridView TemplateField allow us to specify custom controls, multiple fields and Html using a custom template. TemplateField allows us to define a completely customized template for GridView Column. We can bind the data with in template control using binding expression. ASP.NET provides number of ways to take control over the template control. In this post I am going to discuss how we can set template control visibility based on certain condition which depends on the data source data. For example, imagine you have a link button within template field. You want to set visibility if that control based on the some value of your data source.

Let’s consider we have below class for Customer entity. We will create a list of Customers and based on the value of “ShowURL” we are going to display the Web Sites URL.


    /// <summary>
    /// Customer Class
    /// </summary>
    internal sealed class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string WebSite { get; set; }
        public bool ShowURL { get; set; }
    }

Here’s the code snippet for creating List and binding with GridView Control.

  /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            List<Customer> emps = new List<Customer>()
            {
                new Customer{ID=1, Name="Customer 1",WebSite="http://abhijitjana.net",ShowURL=true},
                new Customer{ID=2, Name="Customer 2",WebSite="http://abhisheksur.com",ShowURL=false},
                new Customer{ID=3, Name="Customer 3",WebSite="http://jebarson.info" ,ShowURL=true},
                new Customer{ID=4, Name="Customer 4", WebSite="http://atulvarma.com", ShowURL=false}

                };
            myGrid.DataSource = emps;
            myGrid.DataBind();
        }

In this example we are going to illustrate the binding with TemplateField, so here is the design view of GridView where we have Two column with two different template field. First one is the container of Name and second on is the container of Web Site.

image

Below images shows the output of the above binding.

image

Well, as of now all the site link are getting displayed in the GridView. But we have to display the links based on the value of “ShowURL”  field.

The most common solution we can find is “set visibility during GridView RowDataBound Event” as shown in below

/// <summary>
        /// Handles the RowDataBound event of the myGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void myGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Customer cust = e.Row.DataItem as Customer;
                if (!cust.ShowURL)
                {
                    LinkButton lnkWebURL = e.Row.FindControl("lnk") as LinkButton;
                    if (lnkWebURL != null)
                    {
                        lnkWebURL.Visible = false;
                    }
                }
            }
        }

Above code will hide the link button from the GridView as shown in below image.

image

Well, do we really need to override myGrid_RowDataBound() for this small task ? Can’t we do it using Binding Expression. One similar question had  asked over  at Code Project and I am going to share the answer  which I have provided .

We can use Operator with in Bind Expression. Hence, we can set the visibility of Control using Binding Expression. We really don’t need to write code in RowDataBound just set the visibility of LinkButton as shown in below

image

How it works ?

This will do exactly we did in myGrid_RowDataBound() event. But we followed a different approach.  Eval(“ShowURL”) find evaluate the value of ShowURL From the GridView data source and then set the properties of LinkButton Visibility.  Based on the visible properties of LinkButton, controls renders on page.

We can also use any conditional operator with in the  Binding Expression as well as shown in below

image

That’s all. Very simple, but this will give you some idea to think on using Binding Expression in different ways as well.

Hope this helps.

Cheers !

Aj

8 thoughts on “Dynamically set control visibility inside ItemTemplate’s of GridView using Bind Expression

  1. Could you please post a solution for setting Visibility ‘true’ or ‘false’ to a TemplateField of a GridView for certain condition?

  2. How about this example…

    In my template field there are 3 image buttons: enable, disable, delete

    Dependent on the “status” field the enable and disable buttons are shown/hidden. The delete button is always available

    <asp:ImageButton ID="imgEnableDispatcher" runat="server" ImageUrl="~/images/tick.png" CommandArgument='’ Visible=” OnClick=”btnDispatcherEnable_Click” ToolTip=”Enable Dispatcher” />
    <asp:ImageButton ID="imgDisableDispatcher" runat="server" ImageUrl="~/images/cross.png" CommandArgument='’ Visible=’<%# (Convert.ToBoolean(Eval("status") 4)) %>’ OnClick=”btnDispatcherDisable_Click” ToolTip=”Disable Dispatcher” />
    <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/bin.png" CommandArgument='’ OnClick=”btnDispatcherDelete_Click” ToolTip=”Delete Dispatcher” AlternateText=”Delete Dispatcher” OnClientClick=”return confirm(‘Are you sure you want to delete this dispatcher?’);” />

    Just incase anyone else is scratching their heads over “tag is not well formatted” error make sure that any time you use an <%# you put it in single quotes ' not double quotes "

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s