Data Binding Inline Evaluation

There are time in where you may like to display a certain value inline, depending on the Eval() value that is data bound. At times like this, the ternary operator helps a great deal.

For example, I have a datetime object (“DatePaid”) that is being retrieved from the database using Linq to Sql. And every time the value is null it display the date on the user interface as such “1/01/0001”. I would really like a blank column displayed instead. I achieved this by using the ternary operator inline as below:

   1: <%# Eval("DatePaid") == null ? "&nbsp;" : Eval("DatePaid")

The above translates as such, if “DatePaid” is null then insert blank space “&nbsp;”, else show “DatePaid”

What if you had multiple conditions? Such as If-Else If-Else If-Else. In circumstances like this, it’s probably best handle the values server side, using a data bound event for example.

Hope this helps.


ASP.NET DataView Paging and Sorting.

This post demonstrates the use of the DataView class for simplifying Paging and Sorting operations on a GridView control.

Prior to getting into the workings of it, do note, that I’m using data from Northwind Customers table. Essentially, all I am doing is retrieving the ContactName, CompanyName and Country from all Customers records and returning them as an IEnumerable<T> object in my Data Access Layer.

To begin, I have a GridView control defined with 3 literal controls. Do note, the SortExpression defined on each TemplateField. Also note the OnSorting and OnPageIndexChanging events.

   1: <asp:GridView runat="server" 

   2:               ID="customersGrid" 

   3:               CellPadding="5" 

   4:               CellSpacing="3" AutoGenerateColumns="False" 

   5:               AllowSorting="True" 

   6:               OnSorting="CustomersSorting" 

   7:               AllowPaging="True" 

   8:               PageSize="15" 

   9:               OnPageIndexChanging="CustomersPageChaging" 

  10:               CssClass="gridStyle">

  11:     

  12:     <Columns>

  13:         <asp:TemplateField HeaderText="Name" SortExpression="Name">

  14:             <ItemTemplate>

  15:                 <asp:Literal runat="server" ID="customerName" 

  16:                              Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>'>

  17:                 </asp:Literal>

  18:             </ItemTemplate>

  19:         </asp:TemplateField>

  20:         

  21:         <asp:TemplateField HeaderText="Company" SortExpression="Company">

  22:             <ItemTemplate>

  23:                 <asp:Literal runat="server" ID="customerCompany" 

  24:                              Text='<%# DataBinder.Eval(Container.DataItem, "Company") %>'>

  25:                 </asp:Literal>

  26:             </ItemTemplate>

  27:         </asp:TemplateField>

  28:         

  29:         <asp:TemplateField HeaderText="Country" SortExpression="Country">

  30:             <ItemTemplate>

  31:                 <asp:Literal runat="server" ID="customerCountry" 

  32:                             Text='<%# DataBinder.Eval(Container.DataItem, "Country") %>'>

  33:                 </asp:Literal>

  34:             </ItemTemplate>

  35:         </asp:TemplateField>

  36:     </Columns>

  37: </asp:GridView>

Then on the code-behind, I’ve set up a property called SortOrder. This property keeps track of the ViewState[“SortOrder”] value that is saved on page postbacks.

   1: public string SortOrder

   2: {

   3:     get

   4:     {

   5:         if (ViewState["SortOrder"].ToString() == "DESC")

   6:         {

   7:             ViewState["SortOrder"] = "ASC";

   8:         }

   9:         else

  10:         {

  11:             ViewState["SortOrder"] = "DESC";

  12:         }

  13:  

  14:         return ViewState["SortOrder"].ToString();

  15:     }

  16:     set

  17:     {

  18:         ViewState["SortOrder"] = value;

  19:     }

  20: }

The Page_Load method, sets the SortOrder property to an empty string, then calls a custom method to bind the data to the GridView control.

   1: protected void Page_Load(object sender, EventArgs e)

   2: {

   3:     if(Page.IsPostBack) return;

   4:  

   5:     ViewState["SortOrder"] = "";

   6:     BindCustomersGrid("","");

   7: }

The custom bind method that is called from the Page_Load method takes in 2 string parameters. The parameters define the sort expression and the sort direction.

The method first checks if the sort expression is not an empty string. If it isn’t empty it then proceeds to use the DataView Sort property, prior to binding the data to the GridView control.

   1: private void BindCustomersGrid(string sortExp, string sortDir)

   2: {

   3:     // Custom method is called and DataView object is returned.

   4:     var view = GetCustomerData();

   5:  

   6:     // Check if Sort Expression is available.

   7:     if (sortExp != string.Empty)

   8:     {

   9:         view.Sort = string.Format("{0} {1}", sortExp, sortDir);

  10:     }

  11:  

  12:     // Bind data to GridView control.

  13:     customersGrid.DataSource = view;

  14:     customersGrid.DataBind();

  15: }

The custom method that returns the DataView object as shown in snippet above, is define in snippet below.

   1: private static DataView GetCustomerData()

   2: {

   3:     // Initialise and construct new DataTable

   4:     using (var table = new DataTable())

   5:     {

   6:         table.Columns.Add("Name", typeof(string));

   7:         table.Columns.Add("Company", typeof (string));

   8:         table.Columns.Add("Country", typeof (string));

   9:  

  10:         // Retrieve customer records from database layer

  11:         // and populate DateTable rows.

  12:         foreach (var customer in CustomerData.GetAllCustomers())

  13:         {

  14:             table.Rows.Add(customer.Name, customer.Company, customer.Country);

  15:         }

  16:  

  17:         return table.DefaultView;

  18:     }

  19: }

Now we come to the core part of this post. How do we perform sorting? Well, if you have followed the snippets along you would have noticed the custom bind method takes in 2 parameters. It then checks the sort expression parameter for a value, then uses the DataView Sort property to apply the sorting. Not too complex, but the easier bit is on the GridView OnSorting event as show below. Basically, calling the custom bind method by passing in both, the sort expression and the sort order.

   1: protected void CustomersSorting(object sender, GridViewSortEventArgs e)

   2: {

   3:     // Sorting is performed by calling custom bind method and specifying

   4:     // sort expression as defined in GridView control and the SortOrder

   5:     // property value.

   6:     BindCustomersGrid(e.SortExpression, SortOrder);

   7: }

Now to the next part of the post which is, How do we perform paging?. Well, on the GridView OnPageIndexChanging event, a new page index is set based on the GridViewPageEventArgs passed in, then the custom bind method is called again.

   1: protected void CustomersPageChaging(object sender, GridViewPageEventArgs e)

   2: {

   3:     customersGrid.PageIndex = e.NewPageIndex;

   4:     BindCustomersGrid("", "");

   5: }

Hope the post helps show how easy it is to get Paging and Sorting operations working, through the use of a DataView object.


Follow

Get every new post delivered to your Inbox.