Tuesday, September 28, 2010

Working with List View Control in ASP.Net 3.5

by Suresh Ruddarraju, .Net Developer
Working with List View Control in ASP.Net 3.5

Advantages of ListView
1. ListView is lighter than GridView.
2. It just renders what we type in template field.
3. We can either design the template by ourselves or use the existing layout from the ListView.
4. We can sort the ListView, Select, Insert, Update, Delete.
5. If we need Paging, we can integrate it with DataPager.
6. Compatible with any datasource : LinqDataSource, SqlDataSource, etc.
7. It supports grouping.

Some Sample Screen Shots of this post.







.aspx
<asp:UpdatePanel ID="upClaimantSearch" runat="server">
<ContentTemplate>
<div>
<table width="1000px">
<tr>
<td>
<table width="900px">
<tr>
<td style="width: 890px" align="center">
<%-- Data Pager for the ListView Section --%>
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvTest" PageSize="2">
<Fields>
<asp:TemplatePagerField>
<PagerTemplate>
<table>
<tr id="PageHeaderRow" runat="server">
<%--display like "Page 1 of 2(4 records)" as the pagesize is 2--%>
<td>
Page
<asp:Label runat="server" ID="CurrentPageLabel" Text="<%# Container.TotalRowCount > 0 ? (Container.StartRowIndex / Container.PageSize) + 1 : 0 %>" />
of
<asp:Label runat="server" ID="TotalPagesLabel" Text="<%# Math.Ceiling ((double)Container.TotalRowCount / Container.PageSize) %>" />
(<asp:Label runat="server" ID="TotalItemsLabel" Text="<%# Container.TotalRowCount%>" />
records)
</td>
<td>
<asp:DropDownList ID="ddlGoTo" AutoPostBack="true" runat="server" Width="100px" OnSelectedIndexChanged="ddlGoTo_SelectedIndexChanged" />
</td>
</tr>
</table>
</PagerTemplate>
</asp:TemplatePagerField>
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:ListView ID="lvTest" runat="server" OnItemCommand="lvTest_ItemCommand" OnSorting="lvTest_Sorting"
OnPagePropertiesChanged="lvTest_PagePropertiesChanged" OnDataBound="lvTest_DataBound">
<%--Design Layout with our own --%>
<LayoutTemplate>
<table width="900px">
<tr style="background-color: Scrollbar">
<td align="center">
<table width="900px">
<tr id="headerRow" runat="server">
<td style="width: 225px">
<asp:LinkButton ID="lnkID" runat="server" CommandName="Sort" CommandArgument="ID"
Text="ID"></asp:LinkButton>
</td>
<td style="width: 225px">
<asp:LinkButton ID="lnkName" runat="server" CommandName="Sort" CommandArgument="Name"
Text="Name"></asp:LinkButton>
</td>
<td style="width: 225px">
<asp:LinkButton ID="lnkNumber" runat="server" CommandName="Sort" CommandArgument="Number"
Text="Number"></asp:LinkButton>
</td>
<td style="width: 225px">
<u>
<asp:Label ID="lnkDetails" runat="server" Text="Details" ForeColor="Blue"></asp:Label></u>
</td>
</tr>
<tr id="itemPlaceholder" runat="server" />
</table>
</td>
</tr>
<tr>
<td align="center">
<asp:DataPager ID="SearchDataPagerRD" runat="server" PageSize="2">
<Fields>
<asp:NumericPagerField ButtonType="Link" ButtonCount="2" NextPageText=">>" PreviousPageText="<<" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<%--Item template Gets or sets the custom content for the data item in ListView--%>
<ItemTemplate>
<table width="900px">
<tr>
<td>
<table width="900px">
<tr>
<td style="width: 225px">
<asp:Label ID="lblID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ID")%>' />
</td>
<td style="width: 225px">
<asp:Label ID="lblName" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name")%>' />
</td>
<td style="width: 225px">
<asp:Label ID="lblNumber" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Number")%>' />
</td>
<td style="width: 225px">
<asp:ImageButton ID="btnReview" runat="server" CommandName="Review" ImageUrl="~/Images/Review.JPG"
CommandArgument='<%# DataBinder.Eval(Container, "DataItem.ID") %>' />
</td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
</asp:ListView>
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>

.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class ListViewEx : System.Web.UI.Page
{
//Create a test dataset property
public DataSet TestDataSet
{
get
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("Details");
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name", typeof(String));
dt.Columns.Add("Number", typeof(Int32));

dt.Rows.Add(1, "Abc", 1001);
dt.Rows.Add(2, "Def", 1002);
dt.Rows.Add(3, "Ghi", 1003);
dt.Rows.Add(4, "Xyz", 1004);
return ds;
}
set
{
TestDataSet = value;
}
}

public SortDirection LVSortDirection
{
get
{
if (Session["LVSortDirection"] == null)
{
Session["LVSortDirection"] = SortDirection.Ascending;
}
return (SortDirection)Session["LVSortDirection"];
}

set { Session["LVSortDirection"] = value; }
}

public Int32 LVSearchPageIndex
{
get { return (Int32)Session["LVSearchPageIndex"]; }
set { Session["LVSearchPageIndex"] = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lvTest.DataSource = TestDataSet.Tables[0];
lvTest.DataBind();
}
}

//When we click on review button....
protected void lvTest_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Review")
{
String SelectedItem = (e.CommandArgument.ToString());

String formatExp = "ID='{0}'";

DataRow[] drRows = TestDataSet.Tables[0].Select(String.Format(formatExp, SelectedItem));
string name = String.Empty;
Int32 Number = 0;
if (drRows.Length > 0)
{
foreach (DataRow dr in drRows)
{
name = dr["Name"].ToString();
Number = Convert.ToInt32(dr["Number"]);
}
}
//passing the name and number in sessions to display in next page
Session["Name"] = name.ToString();
Session["Number"] = Number;

Response.Redirect("Default.aspx");
}
}

protected void lvTest_Sorting(object sender, ListViewSortEventArgs e)
{
String direction = String.Empty;
Image directionimg = new Image();

//If sort direction is Asc,change it to desc(as you clicked for sorting)
if (LVSortDirection == SortDirection.Ascending)
{
LVSortDirection = SortDirection.Descending;
direction = "Desc";
directionimg.ImageUrl = "~/Images/SortDownArrow.gif";
}
else
{
LVSortDirection = SortDirection.Ascending;
direction = "Asc";
directionimg.ImageUrl = "~/Images/SortUpArrow.gif";
}

Session["LVSortExpression"] = e.SortExpression;

SetListSortImage(e.SortExpression, directionimg);

SortListView(e.SortExpression, direction);
}

protected void lvTest_PagePropertiesChanged(object sender, EventArgs e)
{
String sortExpression = String.Empty;
Image image = new Image();
String direction = String.Empty;

if (Session["LVSortExpression"] != null)
{
sortExpression = (String)Session["LVSortExpression"];

if (LVSortDirection == SortDirection.Ascending)
{
image.ImageUrl = "~/Images/SortUpArrow.gif";
direction = "Asc";
}
else
{
image.ImageUrl = "~/Images/SortDownArrow.gif";
direction = "Desc";
}

/// Showing Image in ListView Header
SetListSortImage(sortExpression, image);
SortListView(sortExpression, direction);
}
else
{
lvTest.DataSource = TestDataSet;
lvTest.DataBind();
}

Int32 currentPage = (DataPager1.StartRowIndex / DataPager1.PageSize) + 1;
LVSearchPageIndex = currentPage;
}

protected void lvTest_DataBound(object sender, EventArgs e)
{
//Checking for current page
Int32 currentPage = (DataPager1.StartRowIndex / DataPager1.PageSize) + 1;

DropDownList ddlGo = DataPager1.Controls[0].FindControl("ddlGoTo") as DropDownList;

if (DataPager1.TotalRowCount <= DataPager1.PageSize)
{
ddlGo.Visible = false;
}
else
{
//get total number of pages based on total rows count and page size
Int32 totalPages = Convert.ToInt32(Math.Ceiling((Double)DataPager1.TotalRowCount / DataPager1.PageSize));
ddlGo.Items.Clear();
for (Int16 i = 1; i <= totalPages; i++)
{
//bind page numbers automatically to the dropdownlist
ddlGo.Items.Add(i.ToString());
}
ddlGo.SelectedValue = currentPage.ToString();
}
}


protected void ddlGoTo_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList pageno_ddl = sender as DropDownList;
Int32 PageNo = Convert.ToInt32(pageno_ddl.SelectedValue);
Int32 startRowIndex = (PageNo - 1) * DataPager1.PageSize;
DataPager1.SetPageProperties(startRowIndex, DataPager1.PageSize, true);

}

private void SetListSortImage(String sortExpression, Image imgsortArrow)
{
Literal Space = new Literal();
Space.Text = " ";
//Find all the header rows of listview(headerRow is the tr tag id)
Control headerRow = lvTest.FindControl("headerRow");

foreach (HtmlControl sortCell in headerRow.Controls.Cast<HtmlControl>())
{
//Checks all the header link buttons of listview and compares with sortexpression(Clicked item)
LinkButton btnSortField = sortCell.Controls.OfType<IButtonControl>().SingleOrDefault() as LinkButton;
if (btnSortField != null)
{
if (btnSortField.CommandArgument == sortExpression)
{
var imgControl = sortCell.Controls.OfType<WebControl>().Last();

if (imgControl.GetType().FullName != typeof(Image).FullName)
{
//To Provide space between Header linkbuttonText and ImageArrow
sortCell.Controls.Add(Space);

//add the image
sortCell.Controls.Add(imgsortArrow);
}
}
}
}
}

private void SortListView(String SortExpression, String Direction)
{
DataView dv = null;
//Add the datatable to dataview
dv = new DataView(TestDataSet.Tables[0]);

// provide sortExpression space Direction(Desc or Asc)
dv.Sort = SortExpression + " " + Direction;

//Bind the sorted dataview to listview
lvTest.DataSource = dv;
lvTest.DataBind();
}

}

No comments:

Post a Comment