// Este código -fonte é apenas para referência de aprendizado, não para fins comerciais;
// Se você precisar modificar e recorrer ao controle, mantenha as informações de direitos autorais do código -fonte completo!
// Para obter informações sobre a atualização de controle e as novas informações de liberação de controle, preste atenção a www.webdiyer.com.
usando o sistema;
usando System.io;
usando System.Web;
usando system.web.ui;
usando o System.web.ui.webcontrols;
usando o System.web.ui.htmlControls;
Usando System.Collection.Specialized;
usando System.Text;
usando o System.comPonsonModel;
Usando System.comPonentMol.Design;
usando System.Collections;
namespace wuqi.webdiyer
{{
#Region AspNetPager Server Control
#Region Control Descrição e exemplo
/// <summary>
/// para controles do servidor para dados de paginação de dados no aplicativo Web ASP.NET.
/// </summary>
/// <Observações> Ao contrário do controle do Datagrid, o próprio controle de paginação ASPNETPAGER não exibe nenhum dado, mas exibe apenas o elemento de navegação da página. Esse controle pode pagar o Datagrid, o Datalist, o repetidor e os controles personalizados. grande!
/// <p> aspnetPager 2.0 Recentemente, adicionou a função de paginação através do URL, que permite que os visitantes digitem diretamente a URL correspondente para acessar qualquer página, e o mecanismo de pesquisa também pode recuperar cada página. </p>
/// <p> Para usar o controle de paginação ASPNETPAGER, pelo menos ele deve especificar seu atributo <ee Cref = "RecordCount"/>, especificar e gravar o programa de processamento do evento <eee Cref = "Pagechanged"/>.
/// <Veja Cref = "RecordCount"/> O atributo especifica o número total de todos os dados a serem pagos na paginação.
/// Se o programa de processamento de eventos <veja cref = "pagechanged"/> não for especificado e escrito, então quando o usuário clica no elemento de navegação da página ou no índice de página de entrada do estilo manual na caixa de texto Index Page e envie -a página .
/// O método de paginação do controle de aspnetPager é basicamente o mesmo que o do DataGrid, ou seja, em seu programa de processamento de eventos <eee Cref = "Pagechanged"/>, o <eee Cref = "PagechangedEventArgs" de <ver Cref = "O valor de" PagechangedEventargs.NewPageIndex "/> é atribuído ao atributo <eere cref =" currentPageIndex "/> de <ver cref =" currentPageIndex "/> e, em seguida, reencontre os novos controles de exibição de dados e dados. </p> </muils>
/// <Exemplo> Os exemplos a seguir mostram como usar aspnetPager para página do datagrid.
/// <code> <! [CDATA [CDATA [
/// <%@ página de página = "c#"%>
/// <%@ importar namespace = "System.data"%>
/// <%@importar namespace = "system.data.sqlclient"%>
/// <%@importar namespace = "System.configuration"%>
/// <%@registra tagprefix = "webdiyer" namespace = "wuqi.webdiyer" Assembly = "AspnetPager"%>
/// <html>
/// <head>
/// <title> Bem -vindo ao webdiyer.com </title>
/// <script runat = "server">
/// sqlConnection Conn;
/// sqlCommand cmd;
/// void page_load (objeto src, EventArgs e)
/// {
// conn = new sqlConnection (configurationsettings.appSettings ["Connstr"];
/// if (! Page.ispostback)
/// {
/// cmd = new sqlCommand ("getNews", conn);
/// cmd.CommandType = CommandType.StoredProcedure;
/// cmd.parameters.add ("@posgeIndex", 1);
/// cmd.parameters.add ("@Pagesize", 1);
/// cmd.parameters.add ("@docount", true);
// conn.open ();
/// pager.recordCount = (int) cmd.executescalal ();
// Conn.Close ();
/// bindData ();
///}
///}
///
/// void bindData ()
/// {
/// cmd = new sqlCommand ("getNews", conn);
/// cmd.CommandType = CommandType.StoredProcedure;
/// cmd.parameters.add ("@posgeIndex", pager.currentPageIndex);
/// cmd.parameters.add ("@pagesize", pager.pagesize);
/// cmd.parameters.add ("@docount", false);
// conn.open ();
/// datagrid1.dataSource = cmd.execherereader ();
/// datagrid1.databind ();
// Conn.Close ();
/// pager.custominfotext = "Registre total: <font color =" blue "> <b>"+pager.recordCount.toString ()+"</font>" ";
/// pager.custominfotext+= "Número total da página: <font color =" azul "> <b>"+pager.pageCount.toString ()+"</font>" ";
/// pager.custominfotext+= "página atual: <font color =" Red "> <b>"+pager.currentpageIndex.toString ()+"</b> </font>"
///}
/// void ChangePage (Object SRC, PagechangedEventArgs e)
/// {
/// pager.currentpageIndex = e.newPageIndex;
/// bindData ();
///}
/// </script>
/// <meta http-equiv = "content-language" content = "zh-cn">
/// <meta http-equiv = "content-type" content = "text/html; charset = gb2312">
/// <meta name = "general" content = "editplus">
/// <meta name = "autor" content = "webdiyer ([email protegido])"> ">">
/// </head>
/// <body>
/// <form runat = "server" id = "form1">
/// <asp: datagrid id = "datagrid1" runat = "server"/>
/// <webdiyer: aspnetPager id = "pager"
/// runat = "servidor"
/// Pagesize = "8"
/// numericbuttonCount = "8"
/// exibircustominfosection = "esquerda"
/// PagingButtonsPacing = "0"
/// showInputBox = "sempre"
/// CSSCLASS = "MyPager"
/// horizontalally = "Right"
/// onpagechanged = "changepage"
/// submitbuttonText = "Turn para"
/// numericButtonTextFormatString = "[{0}]"/>
/// </morm>
/// </body>
/// </html>
///]]>
/// </code>
/// <p> O procedimento de armazenamento do servidor SQL usado neste exemplo: </p>
/// <code>
/// <! [CDATA [CDATA [
/// Crie procedimento GetNews
/// (@Pagesize int,
/// @PageIndex int,
@Docount bit)
/// como
/// defina nocorre
/// if (@docount = 1)
/// selecione contagem (id) de notícias
/// outro
/// começar
/// Declare @Indextable tabl
/// Declare @PagElowerBound Int
/// declarar @pageUperbound Int
/// set @PagElowerBound = (@PageIndex-)*@PageSize
/// set @[email protegido] [email protegido]
/// Definir RowCount @PageUperBound
/// Inserir em @Indextable (nid) Selecione ID da Ordem de Notícias por Addtime Desc
/// Selecione O.id, O.Source, O.Title, O.Addtime de notícias
/// e t.id> @PageElowerBound e T.id <= @PageUperBound Order by T.ID
/// fim
/// Defina o Nocount Off
/// IR
///]]>
/// </code> </somemlem>
#Endregion
[DefaultProperty ("Pagesize")]
[DefaultEvent ("Pagechanged")]
[Parsechildrn (false)]
[Persistchildren (false)]
[Descrição ("" Controle de paginação para aplicativos da web asp.net ")]]]]]]]]]]]]]]]]]]]]]]]]]]
[Designer (Typeof (PagerDesigner)]]
[ToolboxData (<{0}: ASPNETPAGER RUNAT = Server> </ {0}: aspnetPager> ")]
Classe pública AspNetPager: painel, inamingContainer, iPostbackeventhandler, iPostbackdatahandler
{{
String privada CSSCLASSNAME;
Private string urlpageIndexName = "Page";
Private bool urlpaging = false;
Private string inputPageIndex;
String privada currenturl = null;
Private namevaluecollection urlparams = null;
/// Obtenha ou defina um valor.
/// </summary>
[Navegue (verdadeiro),
Categoria ("Botão de navegação"), DefaultValue (true), Descrição ("Especifica quando o mouse permanece no botão de navegação, é o prompt de ferramenta de exibição"]]]]]]]]]]]
BOOL Public mostradoVigationToolTip
{{
pegar
{{
objeto obj = viewState ["mostradoVigationToolTip"];
Return (obj == null)?
}
definir
{{
ViewState ["mostrouvigationToolTip"] = value;
}
} /// <summary>
/// Obtenha ou defina a ferramenta de botão de navegação para solicitar o formato de texto.
/// </summary>
[Navegue (verdadeiro),
Categoria ("botão de navegação"),
DefaultValue ("Vire para a página nº {0}"),
Descrição ("Ferramentas de botão de navegação de página Formato de texto Lembrete")]]
String pública
{{
pegar
{{
objeto obj = viewState ["navegationToolTipTextFormatString"];
Return (obj == null)?
}
definir
{{
dica de sequência = valor;
if.Trim ().
tip = "{0}";
ViewState
}
} /// <summary>
/// Obtenha ou defina um valor.
/// </summary>
/// <LMarks>
/// Ao definir esse valor como true e não usar o botão de imagem, o valor do botão de índice de página 1, 2, 3, etc. será substituído pelos caracteres chineses primeiro, dois e três.
/// </comentários>
[Navegue (verdadeiro),
Categoria ("botão de navegação"),
DefaultValue (false),
Descrição ("Se o botão Valor do índice da página é substituído pelos números chineses primeiro, segundo e terceiro"]]]]
Public bool chinesepageIndex
{{
pegar
{{
objeto obj = viewState ["chinesepageIndex"];
Return (obj == null)?
}
definir
{{
ViewState ["chinesePageIndex"] = value;
}
} /// <summary>
/// Obtenha ou defina o formato de exibição do texto no botão Número de navegação.
/// </summary>
/// <Value>
/// string, especifique o formato de exibição do texto no valor do índice da página da página, o valor padrão é <ver cref = "string.empty"/>, ou seja, a propriedade não está definida. </value>
/// <LMarks>
/// Use o NumericButtonTextFormatString Properties para especificar o formato de exibição do botão Indexado.
/// Se o valor for definido como "[{0}]", o texto do índice será exibido como: [1] [2] [3] ..., defina o valor como "-{0}-", e então gire o texto do índice para: -1--2- -3- ...
/// </comentários>
[Navegue (verdadeiro),
DefaultValue ("") ,,
Categoria ("botão de navegação"),
Descrição ("Exibir formato do texto no botão numérico do índice de página")]]
Public string numericButtonTextFormatString
{{
pegar
{{
objeto obj = viewstate
Return (obj == null)?
}
definir
{{
ViewState ["numericButtonTexTextFormatring"] = value;
}
} /// <summary>
/// Obtenha ou defina o tipo de botão de navegação de paginação, mesmo que o texto ainda esteja na imagem.
/// </summary>
/// <LMarks>
/// Para usar o botão de imagem, você precisa preparar as seguintes fotos: dez valores de 0 a 9 (quando o showPageIndex é definido como true), a primeira página, página anterior, a próxima página, a última página e mais mais e mais página (...) cinco botões fotos (quando o showfirstlast e o showPrevNext estão definidos como true),
/// Se o botão numérico do índice de página atual for necessário para ser diferente de outros botões numéricos do índice de página, você precisará preparar a imagem do botão do índice de página atual;
/// Se a imagem da primeira página desativada, última página, próxima página e última página for diferente da imagem normal do botão, você precisará preparar as imagens desses quatro botões no estado desativado;
/// <p> <b> As regras de nomeação do arquivo de imagem são as seguintes: </b> </p>
/// <p> De 0 a 9 Botões numéricos, a imagem deve ser denominada "Valor+ButtonImagenameExteXexenses+ButtonImageExtentation".
/// ButtonImageExtenting é o nome do sufixo do arquivo de imagem, como .gif ou .jpg, etc., qualquer tipo de arquivo de imagem que possa ser exibido no navegador. Por exemplo, o arquivo de imagem do índice da página "1" pode ser nomeado "1.gif" ou "1.jpg",
/// Quando você possui dois ou mais conjuntos de arquivos de imagem, você pode distinguir diferentes conjuntos de diferentes conjuntos de imagens, especificando o valor do atributo ButtonImagenamextent. "1.gif". breve. </p>
/// <p> O nome do arquivo de imagem do botão Primeira página começa com "First". Se o ButtonImagenameExketnsion usa a ButtonImagenamextension depende das configurações do botão numérico e se há mais imagens. </p>
/// </comentários>
/// <semel>
/// o seguinte exemplo de fragmento de código se estiver usando o botão de imagem:
/// <p>
/// <code> <! [CDATA [CDATA [
/// <webdiyer: aspnetPager runat = "servidor"
/// id = "pager1"
/// onpagechanged = "changepage"
/// pagingButtonType = "Image"
/// ImagePath = "Images"
/// buttonImagenamextent = "n"
/// desabilledButtonimagenameExtension = "g"
/// buttonImageExnt = "gif"
/// cputtonImagenamexension = "r"
/// PagingButtonspacing = 5/>
///]]>
/// </code>
/// </p>
/// </exemplo>
[Navegue (verdadeiro),
DefaultValue (PagingButtonType.text),
Categoria ("botão de navegação"),
Descrição
Public PagingButtonType PagingButtisepe
{{
pegar
{{
objeto obj = viewstate
Return (obj == null)?
}
definir
{{
ViewState
}
} /// <summary>
/// Obtenha ou defina o tipo de botão numérico de navegação, que é válido apenas quando o PagingButtonType estiver definido para a imagem.
/// </summary>
/// <LMarks>
/// Quando você define o PagingButtonType como imagem, quando você não deseja que o botão numérico do índice de página use a imagem, você pode definir o valor para o texto, o que fará com que o botão de dados do índice da página use o texto em vez do botão de imagem .
/// </comentários>
[Navegue (verdadeiro),
DefaultValue (PagingButtonType.text),
Categoria ("botão de navegação"),
Descrição ("Tipo de" Página de navegação numérica botão numérico ")]]]
Public PagingButtonType numericButtonType
{{
pegar
{{
objeto obj = viewstate
Return (obj == null)?
}
definir
{{
ViewState ["numericButtonType"] = value;
}
} /// <summary>
/// Obtenha ou defina o tipo de primeira página, última página, a próxima página e a última página.
/// </summary>
/// <LMarks>
/// Quando você define o PagingButtonType como imagem, mas não deseja usar a imagem para a primeira, próxima página, próxima página e última página, você pode definir o valor para o texto, que fará com que os quatro botões anteriores no anterior Quatro botões usam texto em vez do botão de imagem.
/// </comentários>
[Navegue (verdadeiro),
Categoria ("botão de navegação"),
DefaultValue (PagingButtonType.text),
Descrição
Public PagingButtonType
{{
pegar
{{
objeto obj = viewstate ["navegaçãoButtonType"];
Return (obj == null)?
}
definir
{{
ViewState ["navegaçãoButtonType"] = value;
}
} /// <summary>
/// Obtenha ou defina o tipo de botão "mais páginas" (...), que só é válido quando o PagingButtonType está definido como imagem.
/// </summary>
/// <LMarks>
/// Quando você define o PagingButtonType como imagem, mas não deseja mais páginas (...) para usar imagens, você pode definir esse valor como texto, o que fará com que mais botões de página usem texto em vez do botão de imagem.
/// </comentários>
[Navegue (verdadeiro),
Categoria ("botão de navegação"),
DefaultValue (PagingButtonType.text),
Descrição ("mais páginas" (...) tipo de botão ")]]
Public PagingButtonType MoreButtonpe
{{
pegar
{{
objeto obj = viewState ["maisbuttisepe"];
Return (obj == null)?
}
definir
{{
ViewState ["MoreButtisepe"] = value;
}
} /// <summary>
/// Obtenha ou defina a distância entre o botão de navegação de paginação.
/// </summary>
[Navegue (verdadeiro),
Categoria ("botão de navegação"),
DefaultValue (tipoof (unidade), "5px"),
Descrição
Unidade pública PagingButTonspacing
{{
pegar
{{
objeto obj = viewState ["pagingButtonspacing"];
Return (obj == null)?
}
definir
{{
ViewState ["PAGINGBUTTONSPACING"] = value;
}
} /// <summary>
/// Obtenha ou defina um valor, o que indica se os botões de primeira e última página são exibidos no elemento de navegação da página.
/// </summary>
[Navegue (verdadeiro),
Descrição
Categoria ("botão de navegação"),
DefaultValue (True)]
Public bool showfirstlast
{{
pegar
{{
objeto obj = viewState ["showfirstlast"];
Return (obj == null)?
}
set {ViewState ["showfirtLast"] = value;}
} /// <summary>
/// Obter ou definir um valor, esse valor indica se a página anterior e a próxima página são exibidas no elemento de navegação da página.
/// </summary>
[Navegue (verdadeiro),
Descrição
Categoria ("botão de navegação"),
DefaultValue (True)]
Public Bool ShowPrevNext
{{
pegar
{{
objeto obj = ViewState ["showPrevNext"];
Return (obj == null)?
}
set {viewState ["showPrevNext"] = value;}
} /// <summary>
/// Obtenha ou defina um valor que indique se o botão Valor do índice da página é exibido no elemento de navegação da página.
/// </summary>
[Navegue (verdadeiro),
Descriptando ("se o botão de valor é exibido no elemento de navegação da página"),
Categoria ("botão de navegação"),
DefaultValue (True)]
Public Bool ShowPageIndex
{{
pegar
{{
objeto obj = viewState ["showPageIndex"];
Return (obj == null)?
}
set {ViewState ["ShowPageIndex"] = value;}
} /// <summary>
/// Get ou defina para o texto exibido pelo botão da primeira página.
/// </summary>
[Navegue (verdadeiro),
Descrição ("Texto exibido no botão da primeira página"),
Categoria ("botão de navegação"),
DefaultValue ("<font face =" webdings "> 9 </font>")]]]
Public String FirstPageText
{{
pegar
{{
objeto obj = ViewState ["FirstPageText"];
Return (obj == null)? "<Font face =" webdings "> 9 </font>": (string) obj;
}
set {ViewState ["FirstPageText"] = value;}
} /// <summary>
/// Obtenha ou defina como texto exibido no botão de página anterior.
/// </summary>
[Navegue (verdadeiro),
Descrição ("Texto exibido no botão da página anterior"),
Categoria ("botão de navegação"),
DefaultValue ("<font face =" webdings "> 3 </font>")]]]
String pública prevageText
{{
pegar
{{
objeto obj = ViewState ["prevageText"];
Return (obj == null)? "<Font face =" webdings "> 3 </font>": (string) obj;
}
set {viewState ["prevpageText"] = value;}
} /// <summary>
/// obtenha ou defina o texto exibido pela próxima página.
/// </summary>
[Navegue (verdadeiro),
Descrição ("Texto exibido no botão da próxima página"),
Categoria ("botão de navegação"),
DefaultValue ("<font face =" webdings "> 4 </font>")]]]
String pública NextPageText
{{
pegar
{{
objeto obj = viewState ["nextpageText"];
Return (obj == null)? "<Font face =" webdings "> 4 </font>": (string) obj;
}
set {ViewState ["nextPageText"] = value;}
} /// <summary>
/// Obtenha ou defina o texto exibido como o botão da última página.
/// </summary>
[Navegue (verdadeiro),
Descrição ("Texto exibido no botão da última página"),
Categoria ("botão de navegação"),
DefaultValue ("<font face =" webdings ">: </font>")]]]
String pública LastPageText
{{
pegar
{{
objeto obj = ViewState ["LastPageText"];
Return (obj == null)? "<Font face =" webdings ">: </font>": (string) obj;
}
set {ViewState ["LastPageText"] = value;}
} /// <summary>
/// Obtenha ou defina o número de botões numéricos exibidos ao mesmo tempo no elemento de navegação da página no controle <eee cref = "aspnetPager"/>.
/// </summary>
[Navegue (verdadeiro),
Descrição
Categoria ("botão de navegação"),
DefaultValue (10)]
Public int numericButtonCount
{{
pegar
{{
objeto obj = ViewState ["numericButtonCount"];
Return (obj == null)?
}
set {ViewState ["numericButtonCount"] = value;}
} /// <summary>
/// Obtenha ou defina um valor que especifique se os botões desativados são exibidos.
/// </summary>
/// <LMarks>
/// Este valor é usado para especificar se o botão de navegação de paginação desativado é exibido. Seja o botão da última página será desativado, os botões proibidos não têm link e clique no botão não terá nenhum efeito.
/// </comentários>
[Navegue (verdadeiro),
Categoria ("botão de navegação"),
Descrição ("Se deve mostrar o botão desativado"),
DefaultValue (True)]
Public bool showDisabledButtons
{{
pegar
{{
objeto obj = viewstate ["showDisabledButton"];
Return (obj == null)?
}
definir
{{
ViewState ["ShowDisabledButtons"] = value;
}
}
#Endregion
#Botões de imagem
/// <summary>
/// Obtenha ou defina o caminho do arquivo de imagem ao usar o botão de imagem.
/// </summary>
[Navegue (verdadeiro),
Categoria ("botão de imagem"),
Descriptando ("Ao usar o botão de imagem, especifique o caminho do arquivo de imagem"), "),),
DefaultValue (NULL)]
Public String ImagePath
{{
pegar
{{
string imgpath = (string) viewState ["imagepath"];
if (imgpath! = null)
imgpath = this.rsolveurl (imgpath);
Devolver imgath;
}
definir
{{
string imgpath = value.trim ().
ViewState ["ImagePath"] = (imgpath.endswith ("/")? Imgpath: imgpath+"/";
}
}
/// <summary>
/// Get ou defina ao usar o botão de imagem, o tipo de imagem, como GIF ou JPG, esse valor é o nome do sufixo do arquivo de imagem.
/// </summary>
[Navegue (verdadeiro),
Categoria ("botão de imagem"),
DefaultValue (". Gif"),
Descrição ("Ao usar o botão de imagem, o tipo da imagem, como GIF ou JPG, esse valor é o nome do sufixo do arquivo de imagem")]
Public string buttonImageExtent
{{
pegar
{{
objeto obj = ViewState ["ButtonImageExtent"];
Return (obj == null)?
}
definir
{{
string ext = value.trim ();
ViewState ["ButtonImageExtension"] = (Ext.StartSwith (".")? Ext: ("."+Ext);
}
}
/// <summary>
/// Obtenha ou defina a sequência de sufixo do nome do arquivo de imagem personalizado para distinguir os diferentes tipos de botões.
/// </summary>
/// <muils> <tay> Nota: </ not> Este valor não é um sufixo de arquivo, mas uma string adicionada ao nome da imagem para distinguir diferentes arquivos de imagem, como ::
/// Atualmente, existem dois conjuntos de botões, um dos quais "1" pode ser "1f.gif", e o nome da imagem do "1" no outro conjunto pode ser "1n.gif", do qual f e N São ButtonImagenamextension. </observações>
[Navegue (verdadeiro),
DefaultValue (NULL),
Categoria ("botão de imagem"),
Descrição ("O sufixo do" nome de arquivo de imagem personalizado), como o ButtonImagenamexketece da imagem "1f.gif" is "f" ")]]]]]]]]]]
Public string buttonImageEnamextension
{{
pegar
{{
Retornar (string) ViewState
}
definir
{{
ViewState ["ButtonImagenamextension"] = value;
}
}
/// <summary>
/// Obtenha ou defina o sufixo do nome da imagem do botão de índice de página atual.
/// </summary>
/// <LMarks>
/// Quando <veja cref = "pagingButtonType"/> está definido como imagem, esse atributo permite definir o caractere de sufixo de nome da imagem usado pelo botão de índice de página atual, para que os botões atuais do índice de página possam ser usados de outra página botões de índice.
/// </comentários>
[Navegue (verdadeiro),
DefaultValue (NULL),
Categoria ("botão de imagem"),
Descrição ("Nome da imagem Faculture String do botão de índice de página atual")]]
Public string cputtonImagNamextension
{{
pegar
{{
objeto obj = viewstate
Return (obj == null)?
}
definir
{{
ViewState ["CPUBUTTOLIMAGENAMEXENSENSENT"] = valor;
}
}
/// <summary>
/// Obtenha ou defina o botão de navegação da página desativado String de sufixo.
/// </summary>
/// <LMarks>
/// Quando <veja cref = "PagingButtonType"/> está definido como imagem, esse valor permite definir o botão de navegação da página (incluindo a primeira página, a página anterior, a página anterior, a página anterior, a página anterior, A página anterior, a sequência de sufixo do nome do arquivo de imagem da próxima página e a última página da última página, para que o botão de navegação da página desativado possa ser diferente do botão normal de navegação da página. Se esse valor não estiver definido, o valor padrão será <ver cref = "buttonImageRextent"/>, ou seja, o botão de navegação de página desativado usa a mesma imagem que o botão de navegação de página normal.
/// </comentários>
[Navegue (verdadeiro),
DefaultValue (NULL),
Categoria ("botão de imagem"),
Descrição ("String de volume do nome da imagem do botão de navegação de página desativado")]]
Public String desabilitedButtonimagename Extensão
{{
pegar
{{
objeto obj = viewstate
Return (obj == null)?
}
definir
{{
ViewState
}
}
/// <summary>
/// Especifique o método de alinhamento ao usar o botão de imagem.
/// </summary>
[Navegue (verdadeiro),
descrição
DefaultValue (ImageAlign.Baseline),
categoria ("botão de imagem")]]
Public ImageAlign ButtonIMAGEALIGN
{{
pegar
{{
objeto obj = viewState ["buttonImagealign"];
Return (obj == null)?
}
Definir {ViewState ["ButtonImagealign"] = value;}
}
#Endregion
#Pagamento de #Region
/// <summary>
/// Obtenha ou defina se deve permitir que a URL passe as informações da paginação.
/// </summary>
/// <LMarks>
/// Ative o método de paginação de URL para passar no índice de página que o usuário deseja acessar através do URL.
/// para que todos os dados sejam restaurados para o valor inicial ou precisam ser obtidos em cada paginação. Use o método de paginação de URL não suporta o valor do atributo de alterações dinâmicas no controle de paginação.
/// porque o novo valor do atributo é temporariamente não conseguido passar o URL para a próxima página.
/// </comentários>
/// <semel> Os exemplos a seguir mostram como usar o método de paginação de URL da ASPNETPAGER para pagar o DataGrid (usando o banco de dados de acesso):
/// <code> <! [CDATA [CDATA [
/// <%@registra tagprefix = "webdiyer" namespace = "wuqi.webdiyer" Assembly = "AspnetPager"%>
/// <%@importar namespace = "system.data.oledb"%>
/// <%@ importar namespace = "System.data"%>
/// <%@ página de página = "c#" debug = true%>
/// <html>
/// <head>
/// <title> Bem -vindo ao webdiyer.com </title>
/// <script runat = "server">
/// OLEDBConnection Conn;
/// OLEDBCOMAND CMD;
/// void page_load (objeto src, EventArgs e) {{
/// Conn = new OLEDBConnection ("Provedor = Microsoft.Jet.oledb.4.0; Data Source ="+Server.mappath ("aceite/aspnetPager.mdb");
/// if (! Page.ispostback) {
/// cmd = new OLEDBCommand ("Selecionar contagem (NewsID) da WQNews", Conn);
// conn.open ();
/// pager.recordCount = (int) cmd.executescalal ();
// Conn.Close ();
/// bindData ();
///}
///}
///
/// void bindData () {{)
/// cmd = new OLEDBCommand ("Selecione Newsid, Heading, Source, Addtime do WQNews Order by Addtime Design, Conn); Conn); Conn); Conn); Conn); Conn); Conn); Conn); Conn); Conn); Conn);
/// adaptador OLEDBDATAADAPTER = novo OLEDBDATAADAPTER (CMD);
/// DataSet ds = new DataSet ();
/// adaptador.fill (ds, pager.pagesize*(pager.currentpageIndex-), pager.pagesize, "notícias");
/// dg.datasource = ds.tables ["notícias"];
/// dg.databind ();
///}
///
/// void changepage (objeto src, pagechangedEventArgs e) {{
/// pager.currentpageIndex = e.newPageIndex;
/// bindData ();
///}
///
/// </script>
/// <meta http-equiv = "content-language" content = "zh-cn">
/// <meta http-equiv = "content-type" content = "text/html; charset = gb2312">
/// <meta name = "general" content = "editplus">
/// <meta name = "autor" content = "webdiyer ([email protegido])"> ">">
/// </head>
/// <body>
/// <form runat = "server" id = "form1">
/// <h2 align = "Center"> ASPNETPAGER PAGINE EXEMPLO </H2>
/// <asp: datagrid id = "dg" runat = "servidor"
/// CellPadding = "4" align = "Center"/>
///
/// <webdiyer: aspnetPager runat = "server" id = "pager"
/// onpagechanged = "changepage"
/// horizontalally = "Center"
///
/// Pagesize = "8"
/// showInputBox = "sempre"
/// submitbuttonStyle = "Border: 1px Solid #000066; altura: 20px; largura: 30px"
/// inputboxstyle = "Border: 1px #0000ff Solid; Text-Align: Center"
/// submitbuttonText = "Turn para"
/// urlpaging = "true"
/// urlpageIndexName = "PageIndex"/>
/// </morm>
/// </body>
/// </html>
///]]> </code>
/// </exemplo>
[Navegue (verdadeiro),
categoria ("paging"),
DefaultValue (false),
Descrição ("Se deve usar o URL para passar as informações da paginação para as páginas")]]
Public Bool UrlPaging
{{
pegar
{{
Retornar urlpaging;
}
definir
{{
urlpaging = value;
}
}
/// <summary>
/// Obtenha ou defina quando o método de paginação de URL estiver ativado, e o nome do parâmetro do índice de página a ser transmitido na URL está no URL.
/// </summary>
/// <LMarks>
/// Este atributo permite personalizar o nome do parâmetro do índice de página para passar pelo índice da página de transmissão de URL para evitar repetir com o nome do parâmetro existente.
/// <p> O valor padrão do atributo é "página", ou seja, quando a paginação de URL, o URL exibido na barra de endereço do navegador é semelhante a: </p> http://www.webdiyer.com /aspnetpager/amostras/datagrid_url.aspx?
/// <p> Se o valor for alterado para "PageIndex", o URL acima se tornará: </p> <p> http://www.webdiyer.com/aspnetpager/samples/datagrid_url.aspx?pageIndex = 2 </p>
/// </comentários>
[Navegue (verdadeiro),
DefaultValue ("página"),
categoria ("paging"),
Descrição ("Quando o método de paginação de URL é ativado, o nome do parâmetro do índice de página a ser indicado no URL")]]]
Public string urlpageIndexName
{{
obtenha {return urlpageIndexName;}
set {urlpageIndexName = value;}
}
/// <summary>
/// Obtenha ou defina o índice da página de exibição atual.
/// </summary>
/// <suitorS> Use este atributo para determinar a página atualmente exibida no controle ASPNETPAGER. Este atributo também é usado para controlar a página exibida por programação.
/// <p> <b> Nota: </b> Diferente do currentPageIndex do controle Datagrid, a propriedade CurrentPageIndex do ASPNetPager começa em 1. </p> </muils>
[Readonly (true),
navegável (falso),
Descrição ("Índice da página de exibição atual"),
categoria ("paging"),
DefaultValue (1),
DesignSerializationVisibility (DesignSerializationVisibility.hidden)]
Public int currentPageIndex
{{
pegar
{{
objeto cpage = ViewState ["currentPageIndex"];
int pindex = (cpage == null)?
If (pindex> pageCount && pageCount> 0)
Retornar pageCount;
caso contrário, se (Pindex <1)
Retornar 1;
Retornar Pindex;
}
definir
{{
int cpage = value;
if (cpage <1)
cpage = 1;
Senão se (cpage> this.pageCount)
cpage = this.pageCount;
ViewState ["currentPageIndex"] = cpage;
}
}
/// <summary>
/// Obtenha ou defina o número total de todos os registros que precisam ser paginos.
/// </summary>
/// <LMarks>
/// Quando a página é carregada pela primeira vez, ela deve receber o atributo a todo o número total de registros de paginação na tabela de dados retornados do procedimento de armazenamento ou da instrução SQL. Na página da página, o valor é obtido do ViewState ao retornar, para evitar o acesso ao banco de dados toda vez que a paginação é evitada. O AspNetPager calcula o número total de páginas exigidas por todos os dados com base no número total de dados a serem paginados e o <ee Cref = "PageSize"/> atributos para a paginação, ou seja, o valor de <ver cref = "PageCount" />.
/// </comentários>
/// <semel>
/// O exemplo abaixo mostra como o número total de registros retornados da instrução SQL é atribuído ao atributo:
/// <p>
/// <code> <! [CDATA [CDATA [
/// <html>
/// <head>
/// <title> Bem -vindo ao webdiyer.com </title>
/// <script runat = "server">
/// sqlConnection Conn;
/// sqlCommand cmd;
/// void page_load (objeto src, EventArgs e)
/// {
// conn = new sqlConnection (configurationsettings.appSettings ["Connstr"];
/// if (! Page.ispostback)
/// {
/// cmd = novo sqlCommand ("Selecionar contagem (id) da notícia", conn);
// conn.open ();
/// pager.recordCount = (int) cmd.executescalal ();
// Conn.Close ();
/// bindData ();
///}
///}
///
/// void bindData ()
/// {
/// cmd = new sqlCommand ("getPagedNews", conn);
/// cmd.CommandType = CommandType.StoredProcedure;
/// cmd.parameters.add ("@posgeIndex", pager.currentPageIndex);
/// cmd.parameters.add ("@pagesize", pager.pagesize);
// conn.open ();
/// datagrid1.dataSource = cmd.execherereader ();
/// datagrid1.databind ();
// Conn.Close ();
///}
/// void ChangePage (Object SRC, PagechangedEventArgs e)
/// {
/// pager.currentpageIndex = e.newPageIndex;
/// bindData ();
///}
/// </script>
/// <meta http-equiv = "content-language" content = "zh-cn">
/// <meta http-equiv = "content-type" content = "text/html; charset = gb2312">
/// <meta name = "general" content = "editplus">
/// <meta name = "autor" content = "webdiyer ([email protegido])"> ">">
/// </head>
/// <body>
/// <form runat = "server" id = "form1">
/// <asp: datagrid id = "datagrid1" runat = "server"/>
///
/// <webdiyer: aspnetPager id = "pager" runat = "servidor"
/// Pagesize = "8"
/// numericbuttonCount = "8"
/// mostraCustominfosection = "Antes"
/// showInputBox = "sempre"
/// CSSCLASS = "MyPager"
/// horizontalally = "Center"
/// onpagechanged = "changepage"/>
///
/// </morm>
/// </body>
/// </html>
///]]>
/// </code> </p>
/// <p> O código do procedimento de armazenamento usado neste exemplo é o seguinte: </p>
/// <code> <! [CDATA [CDATA [
/// Crie procedimento getPagedNews
/// (@Pagesize int,
@PageIndex int)
/// como
/// defina nocorre
/// Declare @Indextable tabl
/// Declare @PagElowerBound Int
/// declarar @pageUperbound Int
/// set @PagElowerBound = (@PageIndex-)*@PageSize
/// set @[email protegido] [email protegido]
/// Definir RowCount @PageUperBound
/// Inserir em @Indextable (nid) Selecione ID da Ordem de Notícias por Addtime Desc
/// Selecione O.id, O.Title, O.Source, O.Addtime de notícias
/// e t.id> @pageLowerBound e t.id <[Email Salmly] Pedido por t.id
/// Defina o Nocount Off
/// IR
///]]>
/// </code>
/// </exemplo>
[Navegue (falsa),
description("要分页的所有记录的总数,该值须在程序运行时设置,默认值为225是为设计时支持而设置的参照值。"),
category("data"),
defaultvalue(225)]
public int recordcount
{{
pegar
{{
object obj=viewstate["recordcount"];
return (obj==null)?0:(int)obj;
}
set{viewstate["recordcount"]=value;}
}
/// <summary>
/// 获取当前页之后未显示的页的总数。
/// </summary>
[browsable(false),
designerserializationvisibility(designerserializationvisibility.hidden)]
public int pagesremain
{{
pegar
{{
return pagecount-currentpageindex;
}
}
/// <summary>
/// 获取或设置每页显示的项数。
/// </summary>
/// <remarks>
/// 该值获取或设置数据呈现控件每次要显示数据表中的的数据的项数,aspnetpager根据该值和<see cref="recordcount"/> 来计算显示所有数据需要的总页数,即<see cref="pagecount"/>的值。</remarks>
/// <example>以下示例将<see cref="aspnetpager"/> 设置为允许每页显示8条数据:
/// <code>
/// <![cdata[
/// ...
/// <webdiyer:aspnetpager id="pager" runat="server" pagesize=8 onpagechanged="changepage"/>
/// ...
/// ]]></code></example>
[browsable(true),
description("每页显示的记录数"),
category("分页"),
defaultvalue(10)]
public int pagesize
{{
pegar
{{
object obj=viewstate["pagesize"];
return (obj==null)?10:(int)obj;
}
definir
{{
viewstate["pagesize"]=value;
}
}
/// <summary>
/// 获取在当前页之后还未显示的剩余记录的项数。
/// </summary>
[browsable(false),
designerserializationvisibility(designerserializationvisibility.hidden)]
public int recordsremain
{{
pegar
{{
if(currentpageindex<pagecount)
return recordcount-(currentpageindex*pagesize);
return 0;}
}
/// <summary>
/// 获取所有要分页的记录需要的总页数。
/// </summary>
[browsable(false),
designerserializationvisibility(designerserializationvisibility.hidden)]
public int pagecount
{{
get{return (int)math.ceiling((double)recordcount/(double)pagesize);}
}
#endregion
#region textbox and submit button
/// <summary>
/// 获取或设置页索引文本框的显示方式。
/// </summary>
/// <remarks>
/// 页索引文件框允许用户手式输入要访问的页的索引,当页数非常多时,显示页索引文本框非常方便用户跳转到指定的页,默认情况下,该文本框只有在总页数大于或等于<see cref="showboxthreshold"/> 的值时才显示,否则不显示,要想该文本框任何时候都显示,请将其值设为always,若希望任何时候都不显示,则应设为never。
///</remarks>
[browsable(true),
descrição
category("文本框及提交按钮"),
defaultvalue(showinputbox.auto)]
public showinputbox showinputbox
{{
pegar
{{
object obj=viewstate["showinputbox"];
return (obj==null)?showinputbox.auto:(showinputbox)obj;
}
set{viewstate["showinputbox"]=value;}
}
/// <summary>
/// 获取或设置应用于页索引输入文本框的css类名。
/// </summary>
[browsable(true),
category("文本框及提交按钮"),
defaultvalue(null),
description("应用于页索引输入文本框的css类名")]
public string inputboxclass
{{
pegar
{{
return (string)viewstate["inputboxclass"];
}
definir
{{
if(value.trim().length>0)
viewstate["inputboxclass"]=value;
}
}
/// <summary>
/// 获取或设置页索引输入文本框的css样式文本。
/// </summary>
[browsable(true),
category("文本框及提交按钮"),
defaultvalue(null),
description("应用于页索引输入文本框的css样式文本")]
public string inputboxstyle
{{
pegar
{{
return (string)viewstate["inputboxstyle"];
}
definir
{{
if(value.trim().length>0)
viewstate["inputboxstyle"]=value;
}
}
/// <summary>
/// 获取或设置页索引页索引输入文本框前的文本字符串值。
/// </summary>
[browsable(true),
category("文本框及提交按钮"),
defaultvalue(null),
description("页索引输入文本框前的文本内容字符串")]
public string textbeforeinputbox
{{
pegar
{{
return (string)viewstate["textbeforeinputbox"];
}
definir
{{
viewstate["textbeforeinputbox"]=value;
}
}
/// <summary>
/// 获取或设置页索引文本输入框后的文本内容字符串值。
/// </summary>
[browsable(true),
defaultvalue(null),
category("文本框及提交按钮"),
description("页索引输入文本框后的文本内容字符串")]
public string textafterinputbox
{{
pegar
{{
return (string)viewstate["textafterinputbox"];
}
definir
{{
viewstate["textafterinputbox"]=value;
}
}
/// <summary>
/// 获取或设置提交按钮上的文本。
/// </summary>
[browsable(true),
category("文本框及提交按钮"),
defaultvalue("go"),
description("提交按钮上的文本")]
public string submitbuttontext
{{
pegar
{{
object obj=viewstate["submitbuttontext"];
return (obj==null)?"go":(string)obj;
}
definir
{{
if(value.trim().length>0)
viewstate["submitbuttontext"]=value;
}
}
/// <summary>
/// 获取或设置应用于提交按钮的css类名。
/// </summary>
[browsable(true),
category("文本框及提交按钮"),
defaultvalue(null),
descrição
public string submitbuttonclass
{{
pegar
{{
return (string)viewstate["submitbuttonclass"];
}
definir
{{
viewstate["submitbuttonclass"]=value;
}
}
/// <summary>
/// 获取或设置应用于提交按钮的css样式。
/// </summary>
[browsable(true),
category("文本框及提交按钮"),
defaultvalue(null),
description("应用于提交按钮的css样式")]
public string submitbuttonstyle
{{
pegar
{{
return (string)viewstate["submitbuttonstyle"];
}
definir
{{
viewstate["submitbuttonstyle"]=value;
}
}
/// <summary>
/// 获取或设置自动显示页索引输入文本框的最低起始页数。
/// </summary>
/// <remarks>
/// 当<see cref="showinputbox"/> 设为auto(默认)并且要分页的数据的总页数达到该值时会自动显示页索引输入文本框,默认值为30。该选项当<see cref="showinputbox"/> 设为never或always时没有任何作用。
/// </remarks>
[browsable(true),
description("指定当showinputbox设为showinputbox.auto时,当总页数达到多少时才显示页索引输入文本框"),
category("文本框及提交按钮"),
defaultvalue(30)]
public int showboxthreshold
{{
pegar
{{
object obj=viewstate["showboxthreshold"];
return (obj==null)?30:(int)obj;
}
set{viewstate["showboxthreshold"]=value;}
}
#endregion
#region custominfosection
/// <summary>
/// 获取或设置显示用户自定义信息区的方式。
/// </summary>
/// <remarks>
/// 该属性值设为left或right时会在分页导航元素左边或右边划出一个专门的区域来显示有关用户自定义信息,设为never时不显示。
/// </remarks>
[browsable(true),
description("显示当前页和总页数信息,默认值为不显示,值为showcustominfosection.left时将显示在页索引前,为showcustominfosection.right时将显示在页索引后"),
defaultvalue(showcustominfosection.never),
category("自定义信息区")]
public showcustominfosection showcustominfosection
{{
pegar
{{
object obj=viewstate["showcustominfosection"];
return (obj==null)?showcustominfosection.never:(showcustominfosection)obj;
}
set{viewstate["showcustominfosection"]=value;}
}
/// <summary>
/// 获取或设置用户自定义信息区文本的对齐方式。
/// </summary>
[browsable(true),
category("自定义信息区"),
defaultvalue(horizontalalign.left),
description("用户自定义信息区文本的对齐方式")]
public horizontalalign custominfotextalign
{{
pegar
{{
object obj=viewstate["custominfotextalign"];
return (obj==null)?horizontalalign.left:(horizontalalign)obj;
}
definir
{{
viewstate["custominfotextalign"]=value;
}
}
/// <summary>
/// 获取或设置用户自定义信息区的宽度。
/// </summary>
[browsable(true),
category("自定义信息区"),
defaultvalue(typeof(unit),"40%"),
description("用户自定义信息区的宽度")]
public unit custominfosectionwidth
{{
pegar
{{
object obj=viewstate["custominfosectionwidth"];
return (obj==null)?unit.percentage(40):(unit)obj;
}
definir
{{
viewstate["custominfosectionwidth"]=value;
}
}
/// <summary>
/// 获取或设置应用于用户自定义信息区的级联样式表类名。
/// </summary>
[browsable(true),
category("自定义信息区"),
defaultvalue(null),
Descrição
public string custominfoclass
{{
pegar
{{
object obj=viewstate["custominfoclass"];
return (obj==null)?cssclass:(string)obj;
}
definir
{{
viewstate["custominfoclass"]=value;
}
}
/// <summary>
/// 获取或设置应用于用户自定义信息区的css样式文本。
/// </summary>
/// <value>字符串值,要应用于用户自定义信息区的css样式文本。</value>
[browsable(true),
category("自定义信息区"),
defaultvalue(null),
description("应用于用户自定义信息区的css样式文本")]
public string custominfostyle
{{
pegar
{{
object obj=viewstate["custominfostyle"];
return (obj==null)?getstylestring():(string)obj;
}
definir
{{
viewstate["custominfostyle"]=value;
}
}
/// <summary>
/// 获取或设置在显示在用户自定义信息区的用户自定义文本。
/// </summary>
[browsable(true),
category("自定义信息区"),
defaultvalue(null),
Descrição
public string custominfotext
{{
pegar
{{
return (string)viewstate["custominfotext"];
}
definir
{{
viewstate["custominfotext"]=value;
}
}
#endregion
#region others
/// <summary>
/// 获取或设置一个值,该值指定是否总是显示aspnetpager分页按件,即使要分页的数据只有一页。
/// </summary>
/// <remarks>
/// 默认情况下,当要分页的数据小于两页时,aspnetpager不会在页面上显示任何内容,将此属性值设为true时,即使总页数只有一页,aspnetpager也将显示分页导航元素。
/// </remarks>
[browsable(true),
category("behavior"),
defaultvalue(false),
description("总是显示分页控件,即使要分页的数据只要一页")]
public bool alwaysshow
{{
pegar
{{
object obj=viewstate["alwaysshow"];
return (obj==null)?false:(bool)obj;
}
definir
{{
viewstate["alwaysshow"]=value;
}
}
/// <summary>
/// 获取或设置由aspnetpager 服务器控件在客户端呈现的级联样式表(css) 类。
/// </summary>
[browsable(true),
description("应用于控件的css类名"),
category("appearance"),
defaultvalue(null)]
public override string cssclass
{{
get{return base.cssclass;}
definir
{{
base.cssclass=value;
cssclassname=value;
}
}
/// <summary>
/// 获取或设置一个值,该值指示aspnetpager 服务器控件是否向发出请求的客户端保持自己的视图状态,该属性经重写后不允许设为false。
/// </summary>
/// <remarks><see cref="aspnetpager"/> 服务器控件将一些重要的分页信息保存在viewstate中,当使用url分页方式时,虽然视图状态在分页过程中没有任何作用,但若当前页需要回发,则必须启用视图状态以便分页控件能在页面回发后获取回发前的分页状态;当通过页面回发(postback)的方式来分页时,要使aspnetpager正常工作,必须启用视图状态。
/// <p><note>该属性并不能禁止用户用<![cdata[<%@page enableviewstate=false%> ]]>页指令来禁用整个页面的视图状态,当使用此指令并且设置aspnetpager通过页面回发来分页时,aspnetpager因为无法获取保存的信息而不能正常工作。</note></p></remarks>
[browsable(false),
description("是否启用控件的视图状态,该属性的值必须为true,不允许用户设置。"),
defaultvalue(true),
category("behavior")]
public override bool enableviewstate
{{
pegar
{{
return base.enableviewstate;
}
definir
{{
base.enableviewstate=true;
}
}
/// <summary>
/// 获取或设置当用户输入的页索引超出范围(大于最大页索引或小于最小页索引)时在客户端显示的错误信息。
/// </summary>
[browsable(true),
description("当用户输入的页索引超出范围(大于最大页索引或小于最小页索引)时在客户端显示的错误信息。"),
defaultvalue("页数超出范围!"),
category("data")]
public string pageindexoutofrangeerrorstring
{{
pegar
{{
object obj=viewstate["pageindexoutofrangeerrorstring"];
return (obj==null)?"页数超出范围!":(string)obj;
}
definir
{{
viewstate["pageindexoutofrangeerrorstring"]=value;
}
}
/// <summary>
/// 获取或设置当用户输入无效的页索引(负值或非数字)时在客户端显示的错误信息。
/// </summary>
[browsable(true),
description("当用户输入无效的页索引(负值或非数字)时在客户端显示的错误信息。"),
defaultvalue("页索引无效!"),
category("data")]
public string invalidpageindexerrorstring
{{
pegar
{{
object obj=viewstate["invalidpageindexerrorstring"];
return (obj==null)?"页索引无效!":(string)obj;
}
definir
{{
viewstate["invalidpageindexerrorstring"]=value;
}
}
#endregion
#endregion
#region control rendering logic
/// <summary>
/// 重写<see cref="system.web.ui.control.onload"/> 方法。
/// </summary>
/// <param name="e">包含事件数据的<see cref="eventargs"/> 对象。</param>
protected override void onload(eventargs e)
{{
if(urlpaging)
{{
currenturl=page.request.path;
urlparams=page.request.querystring;
string pageindex=page.request.querystring[urlpageindexname];
int index=1;
tentar
{{
index=int.parse(pageindex);
}
pegar {}
onpagechanged(new pagechangedeventargs(index));
}
outro
{
inputpageindex=page.request.form[this.uniqueid+"_input"];
}
base.onload(e);
}
/// <summary>
/// 重写<see cref="system.web.ui.control.onprerender"/>方法。
/// </summary>
/// <param name="e">包含事件数据的<see cref="eventargs"/> 对象。</param>
protected override void onprerender(eventargs e)
{{
if(pagecount>1)
{
string checkscript="<script language="javascript">function docheck(el){var r=new regexp("^s*(d+)s*$");if(r.test(el.value)){if(regexp.$1<1||regexp.$1>"+pagecount.tostring()+"){alert(""+pageindexoutofrangeerrorstring+"");document.all['"+this.uniqueid+"_input'].select();return false;}return true;}alert(""+invalidpageindexerrorstring+"");document.all['"+this.uniqueid+"_input'].select();return false;}</script>";
if((showinputbox==showinputbox.always)||(showinputbox==showinputbox.auto&&pagecount>=showboxthreshold))
{
if(!page.isclientscriptblockregistered("checkinput"))
page.registerclientscriptblock("checkinput",checkscript);
string script="<script language="javascript" > <!-- nfunction buildurlstring(key,value){ var _key=key.tolowercase(); var prms=location.search; if(prms.length==0) return location.pathname+"?"+_key+"="+value; var params=prms.substring(1).split("&"); var newparam=""; var found=false; for(i=0;i<params.length;i++){ if(params[i].split("=")[0].tolowercase()==_key){ params[i]=_key+"="+value; found=true; break; } } if(found) return location.pathname+"?"+params.join("&"); else return location+"&"+_key+"="+value; }n//--> </script>";
if(!page.isclientscriptblockregistered("buildurlscript"))
page.registerclientscriptblock("buildurlscript",script);
}
}
base.onprerender(e);
}
/// <summary>
/// Rewrite the <see Cref = "System.web.ui.webControls.webControl.addattributestorender" method. Add the html attributes and styles that need to be presented to the specified <see Cref = "SYSTEM.WEB.HTMLTEXTEXT writer " />
/// </summary>
/// <param name="writer"></param>
protected override void addattributestorender(htmltextwriter writer)
{{
if(this.page!=null)
this.page.verifyrenderinginserverform(this);
base.addattributestorender(writer);
}
/// <summary>
///重写<see cref="system.web.ui.webcontrols.webcontrol.renderbegintag"/> 方法,将<see cref="aspnetpager"/> 控件的html 开始标记输出到指定的<see cref="system.web.ui.htmltextwriter"/> 编写器中。
/// </summary>
///<param name="writer"><see cref="system.web.ui.htmltextwriter"/>,表示要在客户端呈现html 内容的输出流。</param>
public override void renderbegintag(htmltextwriter writer)
{
bool showpager=(pagecount>1||(pagecount<=1&&alwaysshow));
writer.writeline();
writer.write ("<! ------------------------------------------- -------------------------------------------------------- -----------")
writer.write("aspnetpager v4.3 start");
writer.writeline ("--------------------------------------------- -------------------------------------------------------- -------------------------------------------------------- ----------------
writer.write ("<! ------------------------------------------- -------------------------------------------------------- ------------------");
writer.write("copyright:2003 webdiyer(www.webdiyer.com)");
writer.write(" ---------------------");
writer.writeline(">");
base.renderbegintag(writer);
if(!showpager)
{
writer.write("<!-----因为总页数只有一页,并且alwaysshow属性设为false,aspnetpager不显示任何内容,若要在总页数只有一页的情况下显示aspnetpager,请将alwaysshow属性设为true!");
writer.write("----->");
}
if((showcustominfosection==showcustominfosection.left||showcustominfosection==showcustominfosection.right)&&showpager)
{
writer.addattribute(htmltextwriterattribute.width,"100%");
writer.addattribute(htmltextwriterattribute.style,getstylestring());
if(height!=unit.empty)
writer.addstyleattribute(htmltextwriterstyle.height,height.tostring());
writer.addattribute(htmltextwriterattribute.border,"0");
writer.addattribute(htmltextwriterattribute.cellpadding,"0");
writer.addattribute(htmltextwriterattribute.cellspacing,"0");
writer.renderbegintag(htmltextwritertag.table);
writer.renderbegintag(htmltextwritertag.tr);
writecellattributes(writer,true);
writer.renderbegintag(htmltextwritertag.td);
}
}
/// <summary>
///重写<see cref="system.web.ui.webcontrols.webcontrol.renderendtag"/> 方法,将<see cref="aspnetpager"/> 控件的html 结束标记输出到指定的<see cref="system.web.ui.htmltextwriter"/> 编写器中。
/// </summary>
///<param name="writer"><see cref="system.web.ui.htmltextwriter"/>,表示要在客户端呈现html 内容的输出流。</param>
public override void renderendtag(htmltextwriter writer)
{
if((showcustominfosection==showcustominfosection.left||showcustominfosection==showcustominfosection.right)&&(pagecount>1||(pagecount<=1&&alwaysshow)))
{
writer.renderendtag();
writer.renderendtag();
writer.renderendtag();
}
base.renderendtag(writer);
writer.writeline();
writer.write("<!------------------------------- ");
writer.write("aspnetpager v4.3 end");
writer.write(" --------------------------------");
writer.writeline(">");
writer.writeline();
}
/// <summary>
/// Rewrite the <see Cref = "System.web.ui.webControls.webControl.RenderContents" method to present the content of the control to the specified <see cref = "System.web.ui.htmlTextWriter"/> In the dispositivo.
/// </summary>
/// <param name="writer"><see cref="system.web.ui.htmltextwriter"/>,表示要在客户端呈现html 内容的输出流。</param>
protected override void rendercontents(htmltextwriter writer)
{
if(pagecount<=1&&!alwaysshow)
Retornar;
if(showcustominfosection==showcustominfosection.left)
{{
writer.write(custominfotext);
writer.renderendtag();
writecellattributes(writer,false);
writer.addattribute(htmltextwriterattribute.class,cssclass);
writer.renderbegintag(htmltextwritertag.td);
}
int midpage=(int)((currentpageindex-1)/numericbuttoncount);
int pageoffset=midpage*numericbuttoncount;
int endpage=((pageoffset+numericbuttoncount)>pagecount)?pagecount:(pageoffset+numericbuttoncount);
this.createnavigationbutton(writer,"first");
this.createnavigationbutton(writer,"prev");
if(showpageindex)
{
if(currentpageindex>numericbuttoncount)
createmorebutton(writer,pageoffset);
for(int i=pageoffset+1;i<=endpage;i++)
{
createnumericbutton(writer,i);
}
if(pagecount>numericbuttoncount&&endpage<pagecount)
createmorebutton(writer,endpage+1);
}
this.createnavigationbutton(writer,"next");
this.createnavigationbutton(writer,"last");
if((showinputbox==showinputbox.always)||(showinputbox==showinputbox.auto&&pagecount>=showboxthreshold))
{
writer.write(" ");
if(textbeforeinputbox!=null)
writer.write(textbeforeinputbox);
writer.addattribute(htmltextwriterattribute.type,"text");
writer.addstyleattribute(htmltextwriterstyle.width,"30px");
writer.addattribute(htmltextwriterattribute.value,currentpageindex.tostring());
if(inputboxstyle!=null&&inputboxstyle.trim().length>0)
writer.addattribute(htmltextwriterattribute.style,inputboxstyle);
if(inputboxclass!=null&&inputboxclass.trim().length>0)
writer.addattribute(htmltextwriterattribute.class,inputboxclass);
if(pagecount<=1&&alwaysshow)
writer.addattribute(htmltextwriterattribute.readonly,"true");
writer.addattribute(htmltextwriterattribute.name,this.uniqueid+"_input");
string scriptref="docheck(document.all['"+this.uniqueid+"_input'])";
string postref="if(event.keycode==13){if("+scriptref+")__dopostback('"+this.uniqueid+"',document.all['"+this.uniqueid+"_input'].value);else{event.returnvalue=false;}}";
string keydownscript="if(event.keycode==13){if("+scriptref+"){even
csover 发表于:2006.07.21 08:46 ::分类: ( asp.net ) ::阅读:(464次) :: 评论(0) :: 引用(0)
2006 年07 月20日, 星期四
一个简单的分页控件
采用datagrid的默任的分页方式分页,后来发现对于大的数据量速度很慢,net进程占用系统资源也很大,后来写了个分页的存储过程,每次取数据都只取当前页的,分页是分好了,但是发现翻页就没那么方便了,于是自己写了个简单的分页控件,代码如下(编译以后直接形成dll就可以用)。
sample code:
usando o sistema;
usando system.web.ui;
usando o System.web.ui.webcontrols;
using system.componentmodel;
namespace pageinfocontrol
{
/// <summary>
///webcustomecontrol1的摘要说明
/// </summary>
[defaultproperty('totalrecord'),toolboxdata('<{0}:pageinfo runat=server></{0}:pageinfo>')]
public class pageinfo:system.web.ui.webcontrols.webcontrol,ipostbackeventhandler
{
#region construct method
/// <summary>
///构造函数
/// </summary>
public pageinfo():base(htmltextwritertag.div)
{
}
#endregion
#region variables and constants
public event eventhandler changepageclick;
private string _barbackgroudcolor='#f1f1f1';
private string _barlinkcolor='navy';
private string _barcurrentcolor='#eeeeee';
private int _totalrecord=0;
private int _totalpage=0;
private int _currentpageindex=1;
private int _itemsize=10;
#endregion
#region properties
[description('分页条背景色'),bindable(true),category('appearance'),defaultvalue('#f1f1f1')]
public string barbackgroundcolor
{
get{return _barbackgroundcolor;}
set{_barbackgroundcolor=value;}
}
[description('分页条带链接数字颜色'),bindable(true),category('appearance'),defaultvalue('navy')]
public string barlinkcolor
{{
get{return _barlinkcolor;}
set{_barlinkcolor=value;}
}[description('分页条当前页数字颜色'),bindable(true),category('appearance'),defaultvalue('#eeeeee')]
public string barcurrentcolor
{
get{return _barcurrentcolor;}
set{_barcurrentcolor=value;}
} [description('总记录数'),bindable(false),category('behavior'),defaultvalue(0)]
public int totalrecord
{
get{return _totalrecord;}
definir
{
foreach(char c in system.convert.tostring(value))
{
if(!char.isnumber(c)
{
_totalrecord=0;
Quebrar;
}
_totalrecord=value;
}
} [description('每页显示记录数'),bindable(true),category('behavior'),defaultvalue(0)]
public int pagesize
{
get{return _pagesize;}
definir
{
foreach(char c in system.convert.tostring(value))
{
if(!char.isnumber(c))
{{
_pagesize=0;
Quebrar;
}
}
_pagesize=value;
}
}[description('总页数'),bindable(true),category('behavior'),defaultvalue(0)]
public int totalpage
{
get{return _totalpage;}
}[description('数字规格'),bindable(true),category('behavior'),defaultvalue(10)]
public int itemsize
{
get{return _itemsize;}
definir
{
foreach(char c in system.convert.tostring(value))
{
if(!char.isnumber(c))
{
_itemsize=10;
Quebrar;
}
}
_itemsize=value;
}
}[description('当前页值'),bindable(true),category('behavior'),defaultvalue(1)]
public int currentpageindex
{
get{return _currentpageindex;}
set{_currentpageindex=value;}
}
#endregion
//定义div的样式
protected override void addattributestorender(htmltextwriter writer)
{{
writer.addstyleattribute('white-space','nowrap');
writer.addstyleattribute('padding-top','2px');
writer.addstyleattribute('padding-bottom',2px');
writer.addstyleattribute('width',width.tostring());
writer.addstyleattribute('height',height.tostring());
base.addattributestorender(writer);
}
protected virtual void onpagechangeclick(eventargs e)
{
if(changepageclick!=null)
{
changepageclick(this,e);
}
} public void raisepostbackevent(string eventargument)
{
int pageindex=int.parse(eventargument);
this._currentpageindex=pageindex;
onpagechangeclick(new eventargs());
}
/// <summary>
///将此控件呈现给指定的输出参数
/// </summary>
///<param name='output'>要写出到的html编写器</param>
protected override void rendercontents(htmltextwriter output)
{this._totalpage=((this.totalrecord/pagesize)*this.pagesize==this.totalrecord)?(this.totalrecord/this.pagesize):((this.totalrecord/this.pagesize)+1);
int beginrecord=(this.currentpageindex-1)*this.pagesize+1;
int endrecord=this.currentpageindex*this.pagesize;
string pageinfo='[共<font color=#cc0000>'+this.totalpage.tostring()+'</font>页/当前第<font color=#cc0000>'+this.currentpageindex.tostring()+'</font>页共<font color=#cc0000>'+totalrecord.tostring()+'</font>条记录,当前记录数<font color=#cc0000>'+begingrecord.tostring()+'</font>到<font color=#cc0000>'+endrecord.tostring()+'</font>]';
string pageliststr='';
string pageindexcolor='#0000c0';
int singlenumber=this.totalpage-(totalpage/itemsize)*itemsize; //得到分页后的尾数(比如:总共58页,按10页规格显示,则尾数为8)
int intpageformax=(this.currentpageindex-1)/itemsize;
int minint=(1+itemsize*intpageformax);
int maxint=((intpageformax+1)*itemsize)>totalpage?totalpage:((intpageformax+1)*itemsize);
if(this.totalrecord==0||this.totalpage==0)
{
pageliststr='<font color='+pageindexcolor+'>0</font>';
pageliststr=pageliststr+'[共<font color=#cc0000>0</font>页/当前第<font color=#cc0000>0</font>页共<font color=#cc0000>0</font>条记录,当前记录数<font color=#cc0000>0</font>到<font color=#cc0000>0</font>]';
output.write(pageliststr);
}
outro
{
if(this.totalpage<=this.itemsize)
{
for(int i=1;i<=totalpage;i++)
{
pageindexcolor=currentpageindex==i?'#cc0000':'#0000c0';
if(currentpageindex==i)
pageliststr=pageliststr+'<a title='当前为第['+i+']页' href='#' id=''+this.uniqueid+''><font color='+pageindexcolor+'>'+i.tostring()+'</font></a>';
outro
pageliststr=pageliststr+'<a title='点击转到第['+i+']页' id=''+this.uniqueid+'' href=' javascript:'+page.getpostbackeventreference(this,i.tostring())+''><font color='+pageindexcolor+'>'+i.tostring()+'</font></a>';
}
pageliststr=pageliststr==''?'<font color='+pageindexcolor+'>0</font>':pageliststr;
pageliststr=pageliststr+''+pageinfo;
output.write(pageliststr);
}
outro
{{
for(int i=minint;i<=maxint;i++)
{
pageindexcolor=currentpageindex==i?'#cc0000':'#0000c0';
if(currentpageindex==i)
pageliststr=pageliststr+'<a title='当前为第['+i+']页' href='#' id=''+this.uniqueid+''><font color='+pageindexcolor+'>'+i.tostring()+'</font></a>';
outro
pageliststr=pageliststr+'<a title='点击转到第['+i+']页' id=''+this.uniqueid+'' href=' javascript:'+page.getpostbackeventreference(this,i.tostring())+''><font color='+pageindexcolor+'>'+i.tostring()+'</font></a>';
}
//当当前页数小于itemsize且总的页数大于itemsize时
if(currentpageindex<=itemsize && totalpage>itemsize)
{
pageliststr=pageliststr+'<a id=''+this.uniqueid+'' title='点击转到第['+system.convert.tostring(itemsize+1)+']页' href=' javascript:'+page.getpostbackeventreference(this.system.convert.tostring(itemsize+1))+''>>></a>';
//当当前页数大于itemsize,且总的页数减去当前页数大于等于尾数值页数时
if(this.currentpageindex>itemsize && (totalpage-this.currentpageindex)>=singlenumber)
{
int multiminpageindex=(intpageformax*itemsize);
int multimaxpageindex=((intpageformax+1)*itemsize)+1;
pageliststr='<a id=''+this.uniqueid+'' title='点击转到第['+multiminpageindex+']页' href=' javascrcipt:'+page.getpostbackeventreference(this.multiminpageindex.tostring())+''><<</a>'+pageliststr.trim()+'<a id=''+this.uniqueid+'' title='点击转到第['+multimaxpageindex+']页' href=' javascript:'+page.getpostbackeventreference(this.multimaxpageindex.tostring())+''>>></a>';
}
//当当前页数大于itemsize,且总的页数减去当前页数大于等于尾数值页数时
if(currentpageindex>10 && (totalpage-currentpageindex)<singlenumber)
{
int multiminpageindex=(intpageformax * itemsize);
pageliststr='<a id=''+this.uniqueid+'' title='点击转到第['+multiminpageindex+']页' href=' javascript:'+page.getpostbackeventreference(this,multiminpageindex.tostring ())+''><<</a>'+pageliststr.trim();
}
pageliststr=pageliststr==''?'<font color='+pageindexcolor+'>0</font>':pageliststr;
pageliststr=pageliststr+''+pageinfo;
output.write(pageliststr);
}
}
base.rendercontents(output);
}
}
}
控件中有几个相关的属性,在使用的时候,只需要指定:totalrecord(总记录数)、pagesize(每页的数据记录数)、currentpageindex(当前页面值)、itemsize(分页条显示页面值的规格)
控件中有个changepageclick事件,可以利用“控件id.currentpageindex”属性来获取当前页面值。
注册会员,创建你的web开发资料库,