RSS

Monthly Archives: November 2010

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: , , , , , , ,

pass parameters to popup window with showModalDialog +aspx


Write this code at Header

function Popup() {

var x = document.getElementById(‘<%=txtRegIDS.ClientID %>’).innerText;

//For showModalDialog Popup Window
window.showModalDialog(“view-student-edu-doc.aspx?param1=” + x, null, ‘status:no;dialogWidth:770px;dialogHeight:500px;dialogHide:true;help:no;scroll:no’)

//For Simple Popup Window
// window.open(“view-student-edu-doc.aspx?param1=” + x, ‘window’, ‘width=780,height=620,menubar=no, resizable=no,scrollbars=no,left=280,top=250’)

}

//Html Code

<asp:Button id=”Button1″ Text=”Student Document” OnClientClick=”Popup()” runat=”server” />
<div style=”visibility:hidden”> <asp:Label ID=”txtRegIDS” runat=”server”   ></asp:Label></div>

//Get this Parm value to another Page with querystring and load the specific information

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
if (Request.QueryString[“param1”] != null && Request.QueryString[“param1”] != string.Empty)
{
int ID = Convert.ToInt32(Request.QueryString[“param1”].ToString());
gvStdDocument(ID);
}
}

}
public void gvStdDocument(int RegID)
{

DataSet ds = DALCourseRequirdDocument.GetStudentEduDoc(RegID);

////ViewStudenttDocumentRequestsStatus
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
gv.DataSource = ds;
gv.DataBind();
//    //gvDocmentdetail
}

}

//The gridview data of Popup window

<div>
<asp:GridView ID=”gv” runat=”server” AutoGenerateColumns=”False” Width=”100%” DataKeyNames=”CRD_ID,doc_uploadID”
PageSize=”50″ EmptyDataText=”No record found” CellPadding=”4″ GridLines=”None”>
<HeaderStyle CssClass=”grid_head” />
<RowStyle CssClass=”data_set1″ />
<AlternatingRowStyle CssClass=”data_set1″ />
<Columns>
<asp:TemplateField HeaderText=”Name” ItemStyle-HorizontalAlign=”left”>
<ItemTemplate>
<%#Eval(“DocumentName”).ToString()%>
<asp:HiddenField ID=”hdID” runat=”server” Value='<%# Eval(“CRD_ID”) %>’ />
</ItemTemplate>
<ItemStyle HorizontalAlign=”Left”></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField=”CreatedDate” HeaderText=”Date Date” SortExpression=”ModifiedDate”
DataFormatString=”{0:d}” />
<asp:BoundField DataField=”ModifiedDate” HeaderText=”Upload Date” SortExpression=”ModifiedDate”
DataFormatString=”{0:d}” />
<asp:TemplateField HeaderText=”Actions” ItemStyle-HorizontalAlign=”Left” ItemStyle-Width=”40px”>
<ItemTemplate>
&nbsp;
<asp:ImageButton ID=”ImageButton1″ runat=”server” CommandArgument='<%# Eval(“UploadedDocument”) %>’
ImageUrl=”~/images/Download.jpg” CausesValidation=”False” OnClick=”ImageButton1_Click” />
</ItemTemplate>
<ItemStyle />
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>

/// For Download Code

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
string _Name = ((ImageButton)sender).CommandArgument;
DownloadFile(_Name);
}
protected void DownloadFile(string name)
{

string folderPath = ConfigurationManager.AppSettings.Get(“DocumentPath”) + name; ;

string docPath = Request.PhysicalApplicationPath + folderPath;

System.IO.FileInfo _file = new System.IO.FileInfo(docPath);
if (_file.Exists)
{
Response.Clear();
Response.AddHeader(“Content-Disposition”, “attachment; filename=” + _file.Name);
Response.AddHeader(“Content-Length”, _file.Length.ToString());
Response.ContentType = “application/octet-stream”;
Response.WriteFile(_file.FullName);
Response.End();
}
//else
//{
//    ClientScript.RegisterStartupScript(Type.GetType(“System.String”), “messagebox”, “&lt;script type=\”text/javascript\”&gt;alert(‘Sorry no image found’);</script>”);
//}
}

 
7 Comments

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