RSS

Tag Archives: Gridview Sorting

Gridview Sorting with VB Net with image


Gridview Sorting  with VB.Net

<asp:GridView ID=”grd” runat=”server” Width=”100%” BorderWidth=”0″ BackColor=”#ffffff”

CellPadding=”0″ CellSpacing=”0″ GridLines=”None” ShowFooter=”true” AutoGenerateColumns=”False”

PageSize=”50″ AllowPaging=”true” AllowSorting=”true”>

<PagerSettings Visible=”False” />

<Columns>

<asp:TemplateField>

<HeaderTemplate>

<table border=”0″ cellpadding=”0″ cellspacing=”0″ width=”940px”>

<tr>

<td>

<asp:LinkButton OnClick=”Page_Click” ID=”lnkPageSort” runat=”server”>Article Title</asp:LinkButton>&nbsp;

<asp:Image ID=”imgTitle” runat=”server” ImageAlign=”AbsMiddle” ImageUrl=”images/icons/sortIcon_asc.gif” />

</td>

<td>

<asp:LinkButton OnClick=”Author_Click” ID=”lnkAuthor” runat=”server”>Author</asp:LinkButton>&nbsp;

<asp:Image ID=”imgAuthor” runat=”server” ImageAlign=”AbsMiddle” ImageUrl=”images/icons/sortIcon_asc.gif” />

</td>

<td>

<asp:LinkButton OnClick=”Published_Click” ID=”lnkPublished” runat=”server”>Published</asp:LinkButton>&nbsp;

<asp:Image ID=”imgPublished” runat=”server” ImageAlign=”AbsMiddle” ImageUrl=”images/icons/sortIcon_asc.gif” />

</td>

<td>

<asp:LinkButton OnClick=”Approved_Click” ID=”lnkApproved” runat=”server”>Approved</asp:LinkButton>&nbsp;

<asp:Image ID=”imgApproved” runat=”server” ImageAlign=”AbsMiddle” ImageUrl=”images/icons/sortIcon_asc.gif” />

</td>

<td align=”center”>

<asp:LinkButton OnClick=”DateCreated_Click” ID=”lnkDateCread” runat=”server”>Created</asp:LinkButton>&nbsp;

<asp:Image ID=”imgDateCreated” runat=”server” ImageAlign=”AbsMiddle” ImageUrl=”images/icons/sortIcon_asc.gif” />

</td>

<td align=”center”>

<asp:LinkButton OnClick=”dateModified_Click” ID=”lnkdateModified” runat=”server”>Modified</asp:LinkButton>&nbsp;

<asp:Image ID=”imgdateModified” runat=”server” ImageAlign=”AbsMiddle” ImageUrl=”images/icons/sortIcon_asc.gif” />

</td>

<td>

Actions

</td>

</tr>

</HeaderTemplate>

<ItemTemplate>

<tr>

<td>

<img src=”images/page1.gif” alt=”Edit Page” style=”vertical-align: text-bottom” />&nbsp;<a

href=”newsdetail.aspx?id=<%#Eval(“articleID”)%>”><%#Eval(“articleTitle”)%></a>

</td>

<td>

<%#Eval(“FullName”)%>

</td>

<td>

<%#Eval(“IsPublished”)%>

</td>

<td>

<%#Eval(“IsApproved”)%>

</td>

<td>

<%# DateTimeFormat.formateDate(DataBinder.Eval(Container.DataItem, “dateCreated”))%>

</td>

<td>

<%# DateTimeFormat.formateDate(DataBinder.Eval(Container.DataItem, “dateModified”))%>

</td>

<td>

<a href=”newsdetail.aspx?id=<%#Eval(“articleID”)%>”><strong>Edit</strong></a>&nbsp;&nbsp;|&nbsp;&nbsp;<asp:LinkButton

ID=”lnkDelete” OnClientClick=”return confirm(‘Are you sure you want to delete the record?’);”

runat=”server” CommandName=”cmdDelete” CommandArgument='<%#Eval(“articleID”)%>’><strong>Delete</strong></asp:LinkButton>

</td>

</tr>

</ItemTemplate>

<FooterTemplate>

<tr>

<td colspan=”7″>

&nbsp;

</td>

</tr>

</FooterTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

For Gridview Column set Custom Date Formate

First Create class with DateTimeFormat.vb

In App_Code folder

Public Class DateTimeFormat

Public Shared Function formateDate(ByVal obj As Object) As String

Dim dtFormat As String = “”

Try

If Not obj Is Nothing Then

dtFormat = CType(obj, DateTime).ToString(“MM/dd/yy”) & “&nbsp;” & CType(obj, DateTime).ToString(“h:mm tt”)

End If

Catch ex As Exception

End Try

Return dtFormat

End Function

End Class

Code Behind Side

‘//Global Variables

Public Shared sortOrder() As String = {“ASC”}

Public Shared sortLast() As String = {“ASC”, “Title”}

Dim bolRights As Boolean = False

Public strCMSVersion As String = String.Empty

Public strControlPage As String = String.Empty

Public strSiteURL As String = String.Empty

At Page Load Event

If Not Page.IsPostBack Then

bindData()

End If

1.Function Load Data

Private Sub bindData()

Try

DataInfo = ArticlesBAL.GetArticleAll(Convert.ToInt32(Session(“siteID”)))

bindDataPaging(0)

If DataInfo.Rows.Count < 1 Then

Me.lblNoPage.Text = “There are currently no News to display. You may create a new News now by clicking the “”Add New News”” link above.”

Me.lblNoPage.visible = True

End If

Catch ex As Exception

Throw ex

End Try

End Sub

2.Function DataPage

Private Sub bindDataPaging(ByVal pageIndex As Integer)

Try

If DataInfo.Rows.Count > 0 Then

pnlFooter.Visible = False

Else

pnlFooter.Visible = True

End If

processPages(pageIndex)

Catch ex As Exception

Throw ex

End Try

End Sub

3.ProcessPages

Private Sub processPages(ByVal pageIndex As Integer)

Try

If DataInfo.Rows.Count > grd.PageSize Then

grd.DataSource = DataInfo

grd.DataBind()

Dim pageCount As Integer = 0

pageCount = grd.PageCount

If (pageIndex < 0) Then

grd.PageIndex = 0

ElseIf (pageIndex > pageCount – 1) Then

grd.PageIndex = pageCount – 1

Else

If (pageIndex = 0) Then

btnPrev.Visible = False

imgbtnPrev.Visible = False

btnNext.Visible = True

imgbtnNext.Visible = True

ElseIf (pageIndex = pageCount – 1) Then

btnPrev.Visible = True

imgbtnPrev.Visible = True

btnNext.Visible = False

imgbtnNext.Visible = False

Else

btnPrev.Visible = True

imgbtnPrev.Visible = True

btnNext.Visible = True

imgbtnNext.Visible = True

End If

grd.PageIndex = pageIndex

End If

pnlPaging.Visible = True

lblPageCount.Text = “| ” & (grd.PageIndex + 1).ToString() & ” |” & ” of ” & pageCount.ToString()

End If

grd.DataSource = DataInfo

grd.DataBind()

Catch ex As Exception

Throw ex

End Try

End Sub

4.grid Events

Protected Sub grd_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grd.PageIndexChanging

End Sub

5.For Delete Link Button

Protected Sub grd_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grd.RowCommand

If e.CommandName = “cmdDelete” Then

Dim DocumentID As Integer = e.CommandArgument

ArticlesBAL.DeleteArticle(DocumentID)

Dim pageIndex As Integer = grd.PageIndex

bindData()

bindDataPaging(pageIndex)

End If

End Sub

6.Grid RowCommand Event for Header Image change

Protected Sub grd_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grd.RowDataBound

If sortInfo <> “” Then

If (e.Row.RowType = DataControlRowType.Header) Then

Dim imgSort As Image = e.Row.FindControl(sortInfo)

If sortLast(0) = “DESC” Then

imgSort.ImageUrl = “images/icons/sortIcon_asc.gif”

ElseIf sortLast(0) = “ASC” Then

imgSort.ImageUrl = “images/icons/sortIcon_desc.gif”

End If

Dim lnkbtn As LinkButton = e.Row.FindControl(“lnkApproved”)

lnkbtn.Text = Resources.Resource.lblGridActive

Dim lnksite As LinkButton = e.Row.FindControl(“lnkPublished”)

lnksite.Text = Resources.Resource.lblGridPublish

End If

Else

If (e.Row.RowType = DataControlRowType.Header) Then

Dim lnkbtn As LinkButton = e.Row.FindControl(“lnkApproved”)

lnkbtn.Text = Resources.Resource.lblGridActive

Dim lnksite As LinkButton = e.Row.FindControl(“lnkPublished”)

lnksite.Text = Resources.Resource.lblGridPublish

End If

End If

End Sub

7.Grid Sorting Event

Protected Sub grd_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grd.Sorting

End Sub

8.Grid Header link sorting

Protected Sub Page_Click(ByVal sender As Object, ByVal e As System.EventArgs)

Dim lnkHeader As LinkButton = CType(sender, LinkButton)

sorting(0, “articleTitle”, “imgTitle”)

End Sub

Protected Sub Author_Click(ByVal sender As Object, ByVal e As System.EventArgs)

sorting(0, “FullName”, “imgAuthor”)

End Sub

Protected Sub Published_Click(ByVal sender As Object, ByVal e As System.EventArgs)

sorting(0, “IsPublished”, “imgPublished”)

End Sub

Protected Sub Approved_Click(ByVal sender As Object, ByVal e As System.EventArgs)

sorting(0, “IsApproved”, “imgApproved”)

End Sub

Protected Sub DateCreated_Click(ByVal sender As Object, ByVal e As System.EventArgs)

sorting(0, “dateCreated”, “imgDateCreated”)

End Sub

Protected Sub dateModified_Click(ByVal sender As Object, ByVal e As System.EventArgs)

sorting(0, “dateModified”, “imgdateModified”)

End Sub

8.Sorting Function

Public Sub sorting(ByVal order As Integer, ByVal sortName As String, ByVal imgTitle As String)

Try

Dim dt As Data.DataTable = DataInfo

Dim dtV As New DataView

sortLast(0) = sortOrder(order)

sortLast(1) = sortName

sortInfo = imgTitle

If sortOrder(order) = “DESC” Then

dtV = dt.DefaultView

dtV.Sort = sortName & ” ” & sortOrder(order)

sortOrder(order) = “ASC”

ElseIf sortOrder(order) = “ASC” Then

dtV = dt.DefaultView

dtV.Sort = sortName & ” ” & sortOrder(order)

sortOrder(order) = “DESC”

End If

bindDataPaging(grd.PageIndex)

Catch ex As Exception

Throw ex

End Try

End Sub

9.Next Page Grid

Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click

bindDataPaging(grd.PageIndex + 1)

End Sub

10.Previou Page Grid

Protected Sub btnPrev_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrev.Click

bindDataPaging(grd.PageIndex – 1)

End Sub

11.Go To Specific Page Grid

Protected Sub btnGoToPage_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnGoToPage.Click

bindDataPaging(Convert.ToInt32(Trim(txtGoToPage.Text) – 1))

End Sub

 
Leave a comment

Posted by on April 6, 2011 in Gridview, Vb.Net

 

Tags: ,

Asp.Net GridView Control Custom Sorting and Paging with C#


Introduction

This Article is pleased that the concept custom sorting and declare custom paging in a GridView control in depth. We found a number of questions and forums that talk about sorting GridView with TemplateField columns. So we took the opportunity to own sorting of the GridView control in our own way and easy to explain. Also explains how the image can be enabled or disabled in the header of the GridView control to indicate which column is sorted and was sorted in what order (ascending or descending). By the way, to improve the wealth of this article, we have added custom paging for the GridView control along with the custom sorting function. You can sort the GridView control, GridView navigate between pages without reset sort.

For Gridview

<asp:GridView ID=”gv” runat=”server” AutoGenerateColumns=”False” Width=”100%”
EmptyDataText=”No record found” AllowSorting=”True”
OnSorting=”gv_Sorting”>
<HeaderStyle CssClass=”grid_head” />
<RowStyle CssClass=”data_set1″ />
<AlternatingRowStyle CssClass=”data_set1″ />
<Columns>
<asp:BoundField DataField=”UsersID” HeaderText=”UsersID” Visible=”False”></asp:BoundField>
<asp:TemplateField HeaderText=”Name” ItemStyle-HorizontalAlign=”left” SortExpression=”Email”>
<ItemTemplate>
<%–<a href=”usersdetail.aspx?UsersID=<%#Eval(“UsersID”)%>” title=”Edit category”>–%>
<%#Eval(“FirstName”).ToString()%>&nbsp;<%#Eval(“LastName”).ToString()%>
<%–</a>–%>
</ItemTemplate>
<ItemStyle HorizontalAlign=”Left”></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Email” ItemStyle-HorizontalAlign=”left” SortExpression=”Email”>
<ItemTemplate>
<%#Eval(“Email”)%>
</ItemTemplate>
<ItemStyle HorizontalAlign=”Left”></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Active” ItemStyle-HorizontalAlign=”left” SortExpression=”Active”>
<ItemTemplate>
<%#Eval(“IsActive”)%>
</ItemTemplate>
<ItemStyle HorizontalAlign=”Left”></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField=”DateCreated” HeaderText=”Date Created” DataFormatString=”{0:d}”
SortExpression=”DateCreated” />
<asp:BoundField DataField=”DateModified” HeaderText=”Date Modified” DataFormatString=”{0:d}”
SortExpression=”DateModified” />
<asp:TemplateField HeaderText=”Role” ItemStyle-HorizontalAlign=”left”>
<ItemTemplate>
<%#Eval(“RoleID”)%>
</ItemTemplate>
<ItemStyle HorizontalAlign=”Left”></ItemStyle>
</asp:TemplateField>

</Columns>
</asp:GridView>

Set Gridview Property and Events

set Gridview Property AllowSorting True

AllowSorting=”True”

And

fire Event (Sorting)

OnSorting=”gv_Sorting”

For Custome Paging Write(Past ) this code on Client Side

<table border=”0″ cellpadding=”0″ cellspacing=”0″>
<tr>
<td>
<asp:Label ID=”lblPageInfo” runat=”server”></asp:Label>
&nbsp; &nbsp;
</td>
<td>
<asp:LinkButton ID=”lbtnFirst” runat=”server” CausesValidation=”false” OnClick=”lbtnFirst_Click”>First</asp:LinkButton>
&nbsp; &nbsp;
<asp:LinkButton ID=”lnkbtnPrevious” OnClick=”lnkbtnPrevious_Click” runat=”server”> Previous </asp:LinkButton>
&nbsp;
</td>
<td>
<asp:DataList ID=”dlPaging” runat=”server” RepeatDirection=”Horizontal” OnItemDataBound=”dlPaging_ItemDataBound”
OnItemCommand=”dlPaging_ItemCommand”>
<ItemTemplate>
<asp:LinkButton ID=”lnkbtnPaging” runat=”server” CommandArgument='<%# Eval(“PageIndex”) %>’
CommandName=”lnkbtnPaging” Text='<%# Eval(“PageText”) %>’></asp:LinkButton>&nbsp;
</ItemTemplate>
</asp:DataList>
</td>
<td>
&nbsp;
<asp:LinkButton ID=”lnkbtnNext” OnClick=”lnkbtnNext_Click” runat=”server”>Next</asp:LinkButton>
&nbsp; &nbsp;
<asp:LinkButton ID=”lbtnLast” runat=”server” CausesValidation=”false” OnClick=”lbtnLast_Click”>Last</asp:LinkButton>
</td>
</tr>
</table>

Server Side Code

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindRole();
showUsers();

}
}

//Load Datatable

public void showUsers()
{

DataTable dt = new DataTable();
dt = UsersBAL.GetUsers_All_Parm(ddlRuleType.SelectedValue);
DataView dv = dt.DefaultView;

if (ViewState[“sortexpression”] != null)
{
dv.Sort = ViewState[“sortexpression”].ToString()
+ ” ” + ViewState[“sortdirection”].ToString();
}
pds.DataSource = dv;
pds.AllowPaging = true;
pds.PageSize = 5;
ViewState[“TotalPages”] = pds.PageCount;
this.lblPageInfo.Text = “Page ” + (CurrentPage + 1) + ” of ” + pds.PageCount;

pds.CurrentPageIndex = CurrentPage;
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
lbtnLast.Enabled = !pds.IsLastPage;
lbtnLast.Enabled = !pds.IsLastPage;
gv.DataSource = pds;
gv.DataBind();

doPaging();

}

Sorted Events

protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
ViewState[“sortexpression”] = e.SortExpression;

if (ViewState[“sortdirection”] == null)
{
ViewState[“sortdirection”] = “asc”;
}
else
{
if (ViewState[“sortdirection”].ToString() == “asc”)
{
ViewState[“sortdirection”] = “desc”;
}
else
{
ViewState[“sortdirection”] = “asc”;
}
}
showUsers();
}

Paging Code

#region “Paging ”
PagedDataSource pds = new PagedDataSource();
private void doPaging()
{
DataTable dt = new DataTable();
dt.Columns.Add(“PageIndex”);
dt.Columns.Add(“PageText”);
for (int i = 0; i < pds.PageCount; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt.Rows.Add(dr);
}

dlPaging.DataSource = dt;
dlPaging.DataBind();
}
public int CurrentPage
{

get
{
if (this.ViewState[“CurrentPage”] == null)
return 0;
else
return Convert.ToInt16(this.ViewState[“CurrentPage”].ToString());
}

set
{
this.ViewState[“CurrentPage”] = value;
}

}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl(“lnkbtnPaging”);
if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Font.Bold = true;
}
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals(“lnkbtnPaging”))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
showUsers();
}
}
protected void lnkbtnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
showUsers();
}

protected void lnkbtnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
showUsers();
}
protected void lbtnFirst_Click(object sender, EventArgs e)
{
CurrentPage = 0;
this.showUsers();
}
protected void lbtnLast_Click(object sender, EventArgs e)
{
CurrentPage = (Convert.ToInt32(ViewState[“TotalPages”]) – 1);
this.showUsers();
}

#endregion

Results:

 
1 Comment

Posted by on November 30, 2010 in ASP Dot Net C#

 

Tags: , , , , , , ,