Showing posts with label Data Control. Show all posts
Showing posts with label Data Control. Show all posts

December 20, 2013

In the previous post, I showed how to use the group a ListView by a predefined number of items. Though this can be useful for displaying, it lacks the feature of not being able to group items by column or a range of data. In this post, I will show how to group a ListView by a range of data within a column.  I will the same data as in the previous post and modify it so it is ordered by age as shown below. I have done the ordering manually. I will bind the ListView and display data so it is grouped by age - for examples, it will be grouped by 10-20 years old, 20-30 years old, etc.
In the ListView declaration, I have changed the display to a list rather than the table for convenience. The ListView declaration is below.
ListView declaration
  1.     <asp:ListView ID="lv2" runat="server"ItemPlaceholderID="itemPlaceholder">
  2.  
  3.       <LayoutTemplate>
  4.         <ul>
  5.           <asp:Literal id="itemPlaceholder" runat="server" />
  6.         </ul>
  7.       </LayoutTemplate>
  8.      
  9.  
  10.       <ItemTemplate>
  11.                 <%# AddHeader() %>
  12.           <li><%# Eval("Name") %> : <%# Eval("Age") %></li>
  13.               </ItemTemplate>
  14.  
  15.   </asp:ListView>

I have also added a method AddHeader() as the first item within the Item Template. This method will add a list item that will be marked as the group identifier for the data. Here's the backend code for AddHeader() method. It's quite simple. It's important to note that updates the header property when the range changes and will only outputs the list item when there is a change.
AddHeader()
  1. public string header = string.Empty;
  2. public string AddHeader()
  3. {
  4.     int age = (int)Eval("Age");
  5.     string ans = "";
  6.  
  7.     if (age >= 10 && age < 20)
  8.         ans = "10 - 20";
  9.     else if (age >= 20 && age < 30)
  10.         ans = "20 - 30";
  11.     else if (age >= 30 && age < 40)
  12.         ans = "30 - 40";
  13.     else if (age >= 40 && age < 50)
  14.         ans = "40 - 50";
  15.  
  16.     if (ans == header)
  17.         ans = "";
  18.     else
  19.         header = ans;
  20.  
  21.     if (ans == "")
  22.         return "";
  23.     else
  24.         return "<li class='liheader'>" + ans + "</li>";
  25. }

I have also added css for styling and you can modify it as you see fit. Here's the css and the display when the code is run.
CSS
  1. <style>
  2.     .liheader {
  3.         font-weight:bold; background-color:gray;
  4.     }
  5.     li {
  6.         list-style: none;
  7.         width: 150px;
  8.         border:1px solid gray;
  9.         padding-left:4px;
  10.     }
  11. </style>
image
Here is the full code from code-behind in case you haven’t read my previous post.
Code behind - full page
  1. public partial class GroupList : System.Web.UI.Page
  2. {
  3.     protected void Page_Load(object sender, EventArgs e)
  4.     {
  5.         lv2.DataSource = GetList();
  6.         lv2.DataBind();
  7.     }
  8.  
  9.     private List<PersonClass> GetList()
  10.     {
  11.         List<PersonClass> list = new List<PersonClass>();
  12.  
  13.         list.Add(new PersonClass { Name = "Don", Age = 25 });
  14.         list.Add(new PersonClass { Name = "Andrew", Age = 25 });
  15.         list.Add(new PersonClass { Name = "Janette", Age = 27 });
  16.         list.Add(new PersonClass { Name = "Smith", Age = 30 });
  17.         list.Add(new PersonClass { Name = "Jane", Age = 32 });
  18.         list.Add(new PersonClass { Name = "Glenn", Age = 35 });
  19.         list.Add(new PersonClass { Name = "Jack", Age = 35 });
  20.         list.Add(new PersonClass { Name = "John", Age = 39 });
  21.         list.Add(new PersonClass { Name = "Peter", Age = 39 });
  22.         list.Add(new PersonClass { Name = "Robert", Age = 40 });
  23.         
  24.         return list;
  25.     }
  26.  
  27.     public string header = string.Empty;
  28.     public string AddHeader()
  29.     {
  30.         int age = (int)Eval("Age");
  31.         string ans = "";
  32.  
  33.         if (age >= 10 && age < 20)
  34.             ans = "10 - 20";
  35.         else if (age >= 20 && age < 30)
  36.             ans = "20 - 30";
  37.         else if (age >= 30 && age < 40)
  38.             ans = "30 - 40";
  39.         else if (age >= 40 && age < 50)
  40.             ans = "40 - 50";
  41.  
  42.         if (ans == header)
  43.             ans = "";
  44.         else
  45.             header = ans;
  46.  
  47.         if (ans == "")
  48.             return "";
  49.         else
  50.             return "<li class='liheader'>" + ans + "</li>";
  51.     }
  52. }
  53.  
  54. public class PersonClass
  55. {
  56.     public string Name { get; set; }
  57.     public int Age { get; set; }
  58. }

December 19, 2013

Group Data Item in ListView

In asp.net ListView, there is an option to group item by count - that is group a number items together. In a ListView, usually, the data will appear in the format as set within the Item Template. With the grouping option - the data will appear in groups of x many items where x is set within the GroupItemCount property of the ListView. For example, this would be useful if you choose to diaplay items in a table with 4 columns and rows. In this case, if there 22 rows of data - there will be 6 rows within the table displayed (5 rows of 4 columns and last row with 2 columns of data).

So, to use the grouping - declare the ListView like below.

ListView declaration
  1. <asp:ListView ID="lv1" runat="server" GroupPlaceholderID="groupPlaceholder" ItemPlaceholderID="itemPlaceholder" GroupItemCount="2">
  2.  
  3.     <LayoutTemplate>
  4.       <table id="main" border="1">
  5.         <asp:Literal id="groupPlaceholder" runat="server" />
  6.       </table>
  7.     </LayoutTemplate>
  8.  
  9.     <GroupTemplate>
  10.         <tr><asp:Literal runat="server" id="itemPlaceholder" /></tr>
  11.     </GroupTemplate>
  12.  
  13.               <ItemTemplate>
  14.         <td><%# Eval("Name") %> :  <%# Eval("Age") %></td>
  15.             </ItemTemplate>
  16.  
  17. </asp:ListView>

 

Note that there is a group template and an item template. The group template is where the data items will be placed. The group and item place holder ids are set from the ListView declaration. The place holder controls should be marked with runat="server". Otherwise, it won't run.

In the backend, I have set up a class - PersonClass and created a List of PersonClass objects. Finally, I have binded the List of PersonClass objects to the  ListView. Here's the code for that.

Backend
  1. public partial class GroupList : System.Web.UI.Page
  2. {
  3.     protected void Page_Load(object sender, EventArgs e)
  4.     {
  5.         lv1.DataSource = GetList();
  6.         lv1.DataBind();
  7.     }
  8.  
  9.     private List<PersonClass> GetList()
  10.     {
  11.         List<PersonClass> list = new List<PersonClass>();
  12.  
  13.         list.Add(new PersonClass { Name = "Smith", Age = 30 });
  14.         list.Add(new PersonClass { Name = "John", Age = 39 });
  15.         list.Add(new PersonClass { Name = "Peter", Age = 39 });
  16.         list.Add(new PersonClass { Name = "Jack", Age = 35 });
  17.         list.Add(new PersonClass { Name = "Andrew", Age = 25 });
  18.         list.Add(new PersonClass { Name = "Robert", Age = 40 });
  19.         list.Add(new PersonClass { Name = "Janette", Age = 27 });
  20.         list.Add(new PersonClass { Name = "Jane", Age = 32 });
  21.         list.Add(new PersonClass { Name = "Glenn", Age = 35 });
  22.         list.Add(new PersonClass { Name = "Don", Age = 25 });
  23.         return list;
  24.     }
  25. }
  26.  
  27. public class PersonClass
  28. {
  29.     public string Name { get; set; }
  30.     public int Age { get; set; }
  31. }

Now, if I run the code the following will be displayed. You can see there are 2 columns.

image

If I change the GroupItemCount property to 3, the following screen will be displayed. Now there are 3 columns displayed.

image

December 12, 2013

Add Static Row in ListView

ListView is a standard asp.net data control and it allows lot of customisation of the view to represent data. We can display any html within the ListView as shown in an earlier post. In this post, I will show how to add a static row at the start or end of the ListView. Let's say our ListView initially look below.

December 10, 2013

ListView in asp.net is a great control to display data in any customised format. We can also display images, videos, hyperlinks or pretty much anything that ordinary html can. This is unlike other controls like GridView or at least this is much easier to do with ListView than with GridView for example.
In this scenario, we have a ListView that is binded to a collection that has one of the properties "FileName" which can either be an image or a video. There is no field in the collection that tells whether FileName refers to a video or an image but it's either an image or a video for sure. To display the item - video or image - properly in the ListView, a method is written that compares the file extension and decided whether it's an image or a video. Here's the source code for that.

October 24, 2012

GridView can be used to display tabular data. Sometimes, instead of paging data, it might be user friendly to display all data in a scrollable format.

It's quite easy to implement this using CSS. In the example below, I have got a div element with a GridView in it and have applied styles to the div to allow scrolling. 

GridView
  1. <div style="height:200px; overflow:scroll;">
  2.     <asp:GridView ID="Gv2" runat="server" AutoGenerateColumns="true"
  3.             DataKeyNames="Uid" DataSourceID="EntityDataSource2">
  4.     </asp:GridView>
  5.         
  6.     <asp:EntityDataSource ID="EntityDataSource2" runat="server"
  7.         ConnectionString="name=ProductsEntities"
  8.         DefaultContainerName="ProductsEntities" EnableFlattening="False"
  9.         EntitySetName="Products">
  10.     </asp:EntityDataSource>    
  11. </div>

October 23, 2012

GridView offers ways to customise row and alternate rows' properties. Sometimes it might be useful to highlight certain rows based on the data it contains. For example, we might have a gridview for products and we might want to highlight rows whose products have price less than 100, etc. In this example, I will use entity data source to bind the gridview and based on the price value, highlight the background colour using the RowCreated event.

Here is the code for it.

GridView Markup
  1. <asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="False"
  2.     DataSourceID="EntityDataSource1" OnRowCreated="RowCreated" DataKeyNames="Uid">
  3.     <Columns>            
  4.         <asp:BoundField DataField="ProductId" HeaderText="ProductId"
  5.             SortExpression="ProductId" />
  6.         <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />            
  7.     </Columns>
  8. </asp:GridView>
  9.  
  10.  
  11. <asp:EntityDataSource ID="EntityDataSource1" runat="server"
  12.     ConnectionString="name=ProductsEntities"
  13.     DefaultContainerName="ProductsEntities" EnableFlattening="False"
  14.     EntitySetName="PriceHistories">
  15. </asp:EntityDataSource>
Row Created Event
  1. protected void RowCreated(object sender, GridViewRowEventArgs e)
  2. {
  3.     if (e.Row.DataItem != null)
  4.     {
  5.         double price = (double)((PriceHistory)e.Row.DataItem).Price.Value;
  6.  
  7.         if (price > 100)
  8.             e.Row.BackColor = System.Drawing.Color.FromArgb(200, 200, 100);
  9.     }
  10. }

You might be wondering what PriceHistory class is - this class is defined within the entity model.

GridView is a data control that supports displaying data in a grid layout which is essentially an html table. It has built in support for updating, deleting, sorting and paging data, however, its lack of flexible layout makes it not the best option. For example, if we want to display the result of a search, we don't necessarily want to display the data in a tabular format.

This is where ListView comes in - it provides a highly customisable and flexible layout. ListViwe can contain any html elements in it like div, p, li, table and any other server side controls. Like GridView, it supports updating, deleting and sorting data. It also supports inserting and data grouping. Paging is also supported via DataPager control.

The following is an example of the how to declare and use GridView and ListView.

GridView
  1. <asp:GridView ID="gv" runat="server" AllowPaging="True" AllowSorting="True"
  2.     CellPadding="4" ForeColor="#333333" GridLines="None" EmptyDataText="Data not found">
  3.     <AlternatingRowStyle BackColor="White" />
  4.     <Columns>
  5.         <asp:CommandField ShowEditButton="True" />
  6.         <asp:CommandField ShowSelectButton="True" />
  7.         <asp:CommandField ShowDeleteButton="True" />
  8.     </Columns>
  9.     <EditRowStyle BackColor="#2461BF" />
  10.     <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  11.     <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  12.     <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
  13.     <RowStyle BackColor="#EFF3FB" />
  14.     <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
  15.     <SortedAscendingCellStyle BackColor="#F5F7FB" />
  16.     <SortedAscendingHeaderStyle BackColor="#6D95E1" />
  17.     <SortedDescendingCellStyle BackColor="#E9EBEF" />
  18.     <SortedDescendingHeaderStyle BackColor="#4870BE" />
  19. </asp:GridView>

 

ListView
  1. <asp:ListView ID="LView" runat="server" GroupItemCount="3" GroupPlaceholderID="groupPlaceHolder">
  2.     <LayoutTemplate>
  3.         <div class="layout"><asp:PlaceHolder ID="itemPlaceHolder" runat="server"></asp:PlaceHolder></div>
  4.  
  5.         <asp:DataPager runat="server" ID="ColDataPager" PageSize="10" DataKeyNames="ID"
  6.             OnItemInserted="LView_Insert" InsertItemPosition="LastItem">
  7.           <Fields>
  8.             <asp:NextPreviousPagerField
  9.               ShowFirstPageButton="true" ShowLastPageButton="true"
  10.               FirstPageText="First " LastPageText=" Last"
  11.               NextPageText=" Next " PreviousPageText=" Prev " />
  12.           </Fields>
  13.         </asp:DataPager>
  14.     </LayoutTemplate>
  15.  
  16.     <GroupTemplate>
  17.         <ul><li>
  18.             <asp:PlaceHolder runat="server" ID="groupPlaceHolder"></asp:PlaceHolder>
  19.         </li></ul>
  20.     </GroupTemplate>
  21.  
  22.     <ItemTemplate>
  23.         <span class="l1_n"><%#Eval("column1") %></span>
  24.     </ItemTemplate>
  25.  
  26.     <AlternatingItemTemplate>
  27.         <span class="l1_alt"><%#Eval("column1") %></span>
  28.     </AlternatingItemTemplate>
  29.  
  30.     <ItemSeparatorTemplate>
  31.         <hr />
  32.     </ItemSeparatorTemplate>
  33.  
  34.  
  35.     <InsertItemTemplate>
  36.         <asp:Label runat="server" ID="LColumn1" AssociatedControlID="TBColumn1" Text="Column1"/>
  37.         <asp:TextBox ID="TBColumn1" runat="server" Text='<%#Bind("column1") %>' /><br />
  38.         <asp:LinkButton ID="LbInsert" runat="server" CommandName="Insert" Text="Insert" />
  39.     </InsertItemTemplate>
  40.  
  41. </asp:ListView>

As you can see, it is lot easier to declare and use the GridView compare to ListView, however, the resultant view is more user friendly with ListView as long as you don't enter weird styles for the controls.

September 12, 2012

Asp.Net GridView can be used to display a large amount of data on a page. Sometimes it would be a better design to style the GridView to display with background colours for alternate rows and a different background colour on hover. The GridView control already has AlternateRowStyle property for setting the alternate colours on rows. The hover feature can be implemented by using css styles.

Here is an example of how to declare the GirdView.

GridView
  1. <asp:GridView ID="Grid1" runat="server" CellPadding="4" ForeColor="#333333"
  2.         GridLines="None">
  3.     <AlternatingRowStyle BackColor="White" />
  4.     <EditRowStyle BackColor="#2461BF" />
  5.     <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  6.     <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  7.     <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
  8.     <RowStyle BackColor="#EFF3FB" />
  9.     <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
  10.     <SortedAscendingCellStyle BackColor="#F5F7FB" />
  11.     <SortedAscendingHeaderStyle BackColor="#6D95E1" />
  12.     <SortedDescendingCellStyle BackColor="#E9EBEF" />
  13.     <SortedDescendingHeaderStyle BackColor="#4870BE" />
  14. </asp:GridView>

The AlternateRowStyle property sets the background colour of alternate row and the RowStyle’s BackColor property set the background colour of the row.

The GridView is rendered as a table and the hover feature can be implemented using css as per below.

GridView Css Styles
  1. <style type="text/css">
  2. table tr:hover { background-color:#eee;}
  3. table tr td:hover { background-color:#ccc;}
  4. </style>

September 5, 2012

From .NET framework, data in a GridView can be selected by either row index or data index. The EnablePersistedSelection property of the GridView caters for this feature. By default, EnablePersistedSelection is set to false and data is selected by row index. When this property is set to false and a row is selected, the same row number remains selected when navigated to a different page. When this property is set to true and a row is selected, the same row is not selected on a different page. However, when navigated back to the same page, the selected row remains selected. To set the property to true, the DataKeyNames property needs to be filled in with the data key for the GridView.

Sample code on how to set the properties are below.

GridView Persisted Selection
  1. <asp:GridView ID="GV1" runat="server" EnablePersistedSelection="True"
  2.         DataKeyNames="skuid" CellPadding="4" ForeColor="#333333" GridLines="None">
  3.     <AlternatingRowStyle BackColor="White" />
  4.     <Columns>
  5.         <asp:HyperLinkField DataNavigateUrlFields="skuid"
  6.             DataNavigateUrlFormatString="product.aspx?skuid={0}"
  7.             DataTextField="productName" />
  8.     </Columns>
  9.     <Columns><asp:CommandField ButtonType="Button" ShowSelectButton="true" /></Columns>
  10.     <EditRowStyle BackColor="#2461BF" />
  11.     <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  12.     <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  13.     <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
  14.     <RowStyle BackColor="#EFF3FB" />
  15.     <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
  16.     <SortedAscendingCellStyle BackColor="#F5F7FB" />
  17.     <SortedAscendingHeaderStyle BackColor="#6D95E1" />
  18.     <SortedDescendingCellStyle BackColor="#E9EBEF" />
  19.     <SortedDescendingHeaderStyle BackColor="#4870BE" />
  20.     </asp:GridView>
Reference: Shahed Kazi at AspNetify.com