如何在自定义的继承自GridView的控件中加入PagerTemplate行。 我想实现自定义分页,但不想每个页面都重复去写代码,因此决定扩展GridView空间,问题是如何动态创建PagerTemplate并加入到GridView中主要是想实现不同的翻页方式。我不想用现成的开发好的,未开源的控件。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 简单说就是如何让自定义的继承自GridView的控件,实现自定义翻页 using System;using System.Collections.Generic;using System.ComponentModel;using System.Text;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;namespace Saga.LivePortal.CustomControl{ [ToolboxData("<{0}:MyGridView runat=server></{0}:MyGridView>")] public class MyGridView : System.Web.UI.WebControls.GridView, IPostBackEventHandler, IPostBackDataHandler { /// <summary> /// /// </summary> public MyGridView() { base.SelectedRowStyle.CssClass = "SelectedItem"; base.RowStyle.CssClass = "GridItem"; base.AlternatingRowStyle.CssClass = "GridAltItem"; base.HeaderStyle.CssClass = "GridHeader"; base.EditRowStyle.CssClass = "SelectedItem"; base.RowStyle.Height = 20; } /// <summary> /// /// </summary> public delegate void OnReBindData(); /// <summary> /// /// </summary> public event OnReBindData ReBindData; /// <summary> /// const string stands for the navigate-to-first-page command sent from the grid /// </summary> private const string NAVIGATE_FIRST = "NAV_FIRST"; /// <summary> /// const string stands for the navigate-to-last-page command sent from the grid /// </summary> private const string NAVIGATE_LAST = "NAV_LAST"; /// <summary> /// const string stands for the navigate-to-previous-page command sent from the grid /// </summary> private const string NAVIGATE_PREVIOUS = "NAV_PREVIOUS"; /// <summary> /// const string stands for the navigate-to-next-page command sent from the grid /// </summary> private const string NAVIGATE_NEXT = "NAV_NEXT"; private const string PAGESIZE_CONTROL = "PAGESIZE_CONTROL"; private bool showPageNavigator = true; public bool ShowPageNavigator { get { return showPageNavigator; } set { showPageNavigator = value; } } #region Override GridView methods public override void RenderControl(HtmlTextWriter writer) { try { writer.Write("<table border=\"0\" class=\"table_dark_inside\" width=\"" + this.Width.ToString() + "\" cellpadding=\"0\" cellspacing=\"0\">"); writer.Write("<tr><td align=\"left\" width=\"100%\">"); base.Render(writer); writer.Write("</td></tr>"); if (this.showPageNavigator) { writer.Write("<tr><td>"); DrawPager(writer); writer.Write("</td></tr>"); } writer.Write("</table>"); } catch (Exception e) { System.Diagnostics.Debug.Write(e); } } protected override void OnRowCreated(GridViewRowEventArgs e) { try { if (e.Row.RowType == DataControlRowType.Header) { // Call the GetSortColumnIndex helper method to determine // the index of the column being sorted. int sortColumnIndex = GetSortColumnIndex(); if (sortColumnIndex != -1) { // Call the AddSortImage helper method to add // a sort direction image to the appropriate // column header. AddSortImage(sortColumnIndex, e.Row); } } base.OnRowCreated(e); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); } } /// <summary> /// This is a helper method used to determine the index of the /// column being sorted. If no column is being sorted, -1 is returned. /// </summary> /// <returns></returns> private int GetSortColumnIndex() { // Iterate through the Columns collection to determine the index // of the column being sorted. try { foreach (DataControlField field in this.Columns) { // judge the current sort column ,if first create ,then return columns[0] if ((field.SortExpression == this.SortExpression) && (field.SortExpression != "")) { return this.Columns.IndexOf(field); } } } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); } return -1; } /// <summary> /// This is a helper method used to add a sort direction /// image to the header of the column being sorted. /// </summary> /// <param name="columnIndex"></param> /// <param name="headerRow"></param> private void AddSortImage(int columnIndex, GridViewRow headerRow) { try { // Create the sorting image based on the sort direction. Image sortImage = new Image(); if (this.SortDirection == SortDirection.Ascending) { sortImage.ImageUrl = "~/Images/LivePortal/up.gif"; sortImage.AlternateText = "Ascending Order"; } else { sortImage.ImageUrl = "~/Images/LivePortal/down.gif"; sortImage.AlternateText = "Descending Order"; } // Add the image to the appropriate header cell. headerRow.Cells[columnIndex].Controls.Add(sortImage); } catch (Exception e) { System.Diagnostics.Debug.Write(e); } } protected override void OnInit(EventArgs e) { try { this.PagerSettings.Visible = false; this.AutoGenerateColumns = false; base.OnInit(e); RegisterControlAndScript(); Page.RegisterRequiresPostBack(this); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); } #endregion 接上 /// <summary> /// /// </summary> /// <param name="writer"></param> protected virtual void DrawPager(HtmlTextWriter writer) { try { writer.Write("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"" + this.Width.ToString() + " \">"); writer.Write("<tr height=\"25\" valign=\"middle\">"); writer.Write("<td align=\"right\" width=\"100%\" class=\"GridPager\">Total Page(s): " + this.PageCount + " "); writer.Write("Current Page: <font color=red>" + (this.PageIndex + 1) + "</font> "); writer.Write(GetCommandLink(NAVIGATE_FIRST)); writer.Write(GetCommandLink(NAVIGATE_PREVIOUS)); writer.Write(GetCommandLink(NAVIGATE_NEXT)); writer.Write(GetCommandLink(NAVIGATE_LAST)); writer.Write("Display "); writer.Write(GetPageSizeSelect()); writer.Write("per page"); writer.Write("</td></tr></table>"); } catch (Exception e) { System.Diagnostics.Debug.Write(e); } } /// <summary> /// this method registers two hidden fields and a script block on the page /// </summary> private void RegisterControlAndScript() { try { System.Web.UI.Control pageControl = this.Page.FindControl(PAGESIZE_CONTROL); if (pageControl == null) { this.Page.ClientScript.RegisterHiddenField(PAGESIZE_CONTROL, ""); } if (!this.Page.ClientScript.IsClientScriptBlockRegistered("ChangePageSizeScript")) { StringBuilder scriptBuilder = new StringBuilder(); scriptBuilder.Append("<script language='JavaScript'>\n"); scriptBuilder.Append("function __SetPageCmd(pageSize)\n"); scriptBuilder.Append("{\n"); scriptBuilder.Append("\n var ParamTag = document.getElementById('" + PAGESIZE_CONTROL + "');\n"); scriptBuilder.Append("\n ParamTag.value=pageSize;\n"); scriptBuilder.Append("}\n"); scriptBuilder.Append("</script>"); string script = scriptBuilder.ToString(); this.Page.ClientScript.RegisterClientScriptBlock(typeof(string), "ChangePageSizeScript", script); } } catch (Exception e) { System.Diagnostics.Debug.Write(e); } } /// <summary> /// this method returns the PostBackEventReference of the Grid in its destination page /// </summary> /// <returns>PostBack Event Reference</returns> private string GetPostBackRef(string paramCMD) { return Page.ClientScript.GetPostBackEventReference(this, paramCMD) + ";"; } private string GetCommandLink(string command) { string cmdLink = ""; try { switch (command) { case NAVIGATE_FIRST: cmdLink = "<a class=\"PagerHyperlinkStyle\" href=\"javascript: " + GetPostBackRef("Page$First") + "\">|<</a>"; break; case NAVIGATE_PREVIOUS: cmdLink = "<a class=\"PagerHyperlinkStyle\" href=\"javascript: " + GetPostBackRef("Page$Prev") + "\"><</a>"; break; case NAVIGATE_NEXT: cmdLink = "<a class=\"PagerHyperlinkStyle\" href=\"javascript: " + GetPostBackRef("Page$Next") + "\">></a>"; break; case NAVIGATE_LAST: cmdLink = "<a class=\"PagerHyperlinkStyle\" href=\"javascript: " + GetPostBackRef("Page$Last") + "\">>|</a>"; break; } } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); } return cmdLink + " "; } /// <summary> /// Write Select Page Size List /// </summary> /// <returns>string</returns> private string GetPageSizeSelect() { string selectString = "<select class=\"select\" onchange=\"javascript: __SetPageCmd(this.options[this.selectedIndex].text);" + GetPostBackRef("PageSizeParam") + "\" id=\"SelectPage\">"; try { switch (base.PageSize) { case 5: selectString += "<option selected>5</option><option>10</option><option>15</option>"; break; case 10: selectString += "<option>5</option><option selected>10</option><option>15</option>"; break; case 15: selectString += "<option>5</option><option>10</option><option selected>15</option>"; break; default: selectString += "<option>5</option><option selected>10</option><option>15</option>"; break; } selectString += "</select> "; } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); } return selectString; } #region IPostBackEventHandler Members void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { try { if (ReBindData != null) { ReBindData(); } if (eventArgument == "Page$Next") { if ((this.PageIndex + 1) == this.PageCount) { return; } } if (eventArgument == "Page$Prev") { if ((this.PageIndex + 1) == 1) { return; } } base.RaisePostBackEvent(eventArgument); } catch (Exception e) { System.Diagnostics.Debug.Write(e); } } #endregion #region IPostBackDataHandler Members public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { try { int pageSize = Convert.ToInt32(postCollection[PAGESIZE_CONTROL]); base.PageSize = pageSize; } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); } return true; } public void RaisePostDataChangedEvent() { } #endregion }} 登陆安全问题。 FCKeditor上传图片报错,求解 下载无提示一改如何处理! 表格对齐不正确 脚本求助... 同步更新对方的js文件,并替换js里面的字符串,怎么搞 UpdatePanel与用户自定义控件的问题 web打印怎么自动设置为A3的 easyUI datagrid js无法控制 在ASP.NET中,从一个页面转到另一个页面时,有像C#中的ShowDialogue方法那样的,而不用Response.Redirect和Javascript 如何收取和发送邮件 B/S结构开发例子
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;namespace Saga.LivePortal.CustomControl
{
[ToolboxData("<{0}:MyGridView runat=server></{0}:MyGridView>")]
public class MyGridView : System.Web.UI.WebControls.GridView, IPostBackEventHandler, IPostBackDataHandler
{
/// <summary>
///
/// </summary>
public MyGridView()
{
base.SelectedRowStyle.CssClass = "SelectedItem";
base.RowStyle.CssClass = "GridItem";
base.AlternatingRowStyle.CssClass = "GridAltItem";
base.HeaderStyle.CssClass = "GridHeader";
base.EditRowStyle.CssClass = "SelectedItem";
base.RowStyle.Height = 20;
}
/// <summary>
///
/// </summary>
public delegate void OnReBindData();
/// <summary>
///
/// </summary>
public event OnReBindData ReBindData;
/// <summary>
/// const string stands for the navigate-to-first-page command sent from the grid
/// </summary>
private const string NAVIGATE_FIRST = "NAV_FIRST";
/// <summary>
/// const string stands for the navigate-to-last-page command sent from the grid
/// </summary>
private const string NAVIGATE_LAST = "NAV_LAST";
/// <summary>
/// const string stands for the navigate-to-previous-page command sent from the grid
/// </summary>
private const string NAVIGATE_PREVIOUS = "NAV_PREVIOUS";
/// <summary>
/// const string stands for the navigate-to-next-page command sent from the grid
/// </summary>
private const string NAVIGATE_NEXT = "NAV_NEXT"; private const string PAGESIZE_CONTROL = "PAGESIZE_CONTROL"; private bool showPageNavigator = true; public bool ShowPageNavigator
{
get
{
return showPageNavigator;
}
set
{
showPageNavigator = value;
}
} #region Override GridView methods
public override void RenderControl(HtmlTextWriter writer)
{
try
{
writer.Write("<table border=\"0\" class=\"table_dark_inside\" width=\"" + this.Width.ToString() + "\" cellpadding=\"0\" cellspacing=\"0\">");
writer.Write("<tr><td align=\"left\" width=\"100%\">");
base.Render(writer);
writer.Write("</td></tr>");
if (this.showPageNavigator)
{
writer.Write("<tr><td>");
DrawPager(writer);
writer.Write("</td></tr>");
}
writer.Write("</table>");
}
catch (Exception e)
{
System.Diagnostics.Debug.Write(e);
}
} protected override void OnRowCreated(GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.Header)
{
// Call the GetSortColumnIndex helper method to determine
// the index of the column being sorted.
int sortColumnIndex = GetSortColumnIndex(); if (sortColumnIndex != -1)
{
// Call the AddSortImage helper method to add
// a sort direction image to the appropriate
// column header.
AddSortImage(sortColumnIndex, e.Row);
}
}
base.OnRowCreated(e);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex);
}
} /// <summary>
/// This is a helper method used to determine the index of the
/// column being sorted. If no column is being sorted, -1 is returned.
/// </summary>
/// <returns></returns>
private int GetSortColumnIndex()
{
// Iterate through the Columns collection to determine the index
// of the column being sorted.
try
{
foreach (DataControlField field in this.Columns)
{
// judge the current sort column ,if first create ,then return columns[0]
if ((field.SortExpression == this.SortExpression) && (field.SortExpression != ""))
{
return this.Columns.IndexOf(field);
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex);
}
return -1;
} /// <summary>
/// This is a helper method used to add a sort direction
/// image to the header of the column being sorted.
/// </summary>
/// <param name="columnIndex"></param>
/// <param name="headerRow"></param>
private void AddSortImage(int columnIndex, GridViewRow headerRow)
{
try
{
// Create the sorting image based on the sort direction.
Image sortImage = new Image();
if (this.SortDirection == SortDirection.Ascending)
{
sortImage.ImageUrl = "~/Images/LivePortal/up.gif";
sortImage.AlternateText = "Ascending Order";
}
else
{
sortImage.ImageUrl = "~/Images/LivePortal/down.gif";
sortImage.AlternateText = "Descending Order";
}
// Add the image to the appropriate header cell.
headerRow.Cells[columnIndex].Controls.Add(sortImage);
}
catch (Exception e)
{
System.Diagnostics.Debug.Write(e);
}
} protected override void OnInit(EventArgs e)
{
try
{
this.PagerSettings.Visible = false;
this.AutoGenerateColumns = false;
base.OnInit(e);
RegisterControlAndScript();
Page.RegisterRequiresPostBack(this);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex);
}
} protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="writer"></param>
protected virtual void DrawPager(HtmlTextWriter writer)
{
try
{
writer.Write("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"" + this.Width.ToString() + " \">");
writer.Write("<tr height=\"25\" valign=\"middle\">");
writer.Write("<td align=\"right\" width=\"100%\" class=\"GridPager\">Total Page(s): " + this.PageCount + " ");
writer.Write("Current Page: <font color=red>" + (this.PageIndex + 1) + "</font> ");
writer.Write(GetCommandLink(NAVIGATE_FIRST));
writer.Write(GetCommandLink(NAVIGATE_PREVIOUS));
writer.Write(GetCommandLink(NAVIGATE_NEXT));
writer.Write(GetCommandLink(NAVIGATE_LAST));
writer.Write("Display ");
writer.Write(GetPageSizeSelect());
writer.Write("per page");
writer.Write("</td></tr></table>");
}
catch (Exception e)
{
System.Diagnostics.Debug.Write(e);
}
}
/// <summary>
/// this method registers two hidden fields and a script block on the page
/// </summary>
private void RegisterControlAndScript()
{
try
{
System.Web.UI.Control pageControl = this.Page.FindControl(PAGESIZE_CONTROL);
if (pageControl == null)
{
this.Page.ClientScript.RegisterHiddenField(PAGESIZE_CONTROL, "");
} if (!this.Page.ClientScript.IsClientScriptBlockRegistered("ChangePageSizeScript"))
{
StringBuilder scriptBuilder = new StringBuilder();
scriptBuilder.Append("<script language='JavaScript'>\n");
scriptBuilder.Append("function __SetPageCmd(pageSize)\n");
scriptBuilder.Append("{\n");
scriptBuilder.Append("\n var ParamTag = document.getElementById('" + PAGESIZE_CONTROL + "');\n");
scriptBuilder.Append("\n ParamTag.value=pageSize;\n");
scriptBuilder.Append("}\n");
scriptBuilder.Append("</script>");
string script = scriptBuilder.ToString();
this.Page.ClientScript.RegisterClientScriptBlock(typeof(string), "ChangePageSizeScript", script);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.Write(e);
}
}
/// <summary>
/// this method returns the PostBackEventReference of the Grid in its destination page
/// </summary>
/// <returns>PostBack Event Reference</returns>
private string GetPostBackRef(string paramCMD)
{
return Page.ClientScript.GetPostBackEventReference(this, paramCMD) + ";";
} private string GetCommandLink(string command)
{
string cmdLink = "";
try
{
switch (command)
{
case NAVIGATE_FIRST:
cmdLink = "<a class=\"PagerHyperlinkStyle\" href=\"javascript: " + GetPostBackRef("Page$First") + "\">|<</a>";
break;
case NAVIGATE_PREVIOUS:
cmdLink = "<a class=\"PagerHyperlinkStyle\" href=\"javascript: " + GetPostBackRef("Page$Prev") + "\"><</a>";
break;
case NAVIGATE_NEXT:
cmdLink = "<a class=\"PagerHyperlinkStyle\" href=\"javascript: " + GetPostBackRef("Page$Next") + "\">></a>";
break;
case NAVIGATE_LAST:
cmdLink = "<a class=\"PagerHyperlinkStyle\" href=\"javascript: " + GetPostBackRef("Page$Last") + "\">>|</a>";
break;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex);
}
return cmdLink + " ";
} /// <summary>
/// Write Select Page Size List
/// </summary>
/// <returns>string</returns>
private string GetPageSizeSelect()
{
string selectString = "<select class=\"select\" onchange=\"javascript: __SetPageCmd(this.options[this.selectedIndex].text);" + GetPostBackRef("PageSizeParam") + "\" id=\"SelectPage\">";
try
{
switch (base.PageSize)
{
case 5:
selectString += "<option selected>5</option><option>10</option><option>15</option>";
break;
case 10:
selectString += "<option>5</option><option selected>10</option><option>15</option>";
break;
case 15:
selectString += "<option>5</option><option>10</option><option selected>15</option>";
break;
default:
selectString += "<option>5</option><option selected>10</option><option>15</option>";
break;
}
selectString += "</select> ";
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex);
}
return selectString;
}
#region IPostBackEventHandler Members void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
try
{
if (ReBindData != null)
{
ReBindData();
}
if (eventArgument == "Page$Next")
{
if ((this.PageIndex + 1) == this.PageCount)
{
return;
}
}
if (eventArgument == "Page$Prev")
{
if ((this.PageIndex + 1) == 1)
{
return;
}
}
base.RaisePostBackEvent(eventArgument);
}
catch (Exception e)
{
System.Diagnostics.Debug.Write(e);
}
} #endregion #region IPostBackDataHandler Members public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
{
try
{
int pageSize = Convert.ToInt32(postCollection[PAGESIZE_CONTROL]);
base.PageSize = pageSize;
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex);
}
return true;
} public void RaisePostDataChangedEvent()
{ } #endregion
}
}