自定义DataGrid控件的分页器






3.71/5 (10投票s)
2005年7月13日
4分钟阅读

80242

872
如何自定义 DataGrid 控件的分页器。
引言
在本文中,我将展示如何自定义 DataGrid
控件的分页器。我们将首先了解如何访问包含分页器的行,然后了解如何根据我们的需要操作它。
如何获取 DataGrid 中包含分页器的行的控制权
让我们看一下图 1.0,它显示了一个 DataGrid
控件,其中显示了一些行,每行显示一个数字。
最后一行是我们要访问的。访问它之后,我们想在此行的最右侧添加一些文本,如下图所示
现在我们知道了我们想要实现的目标,让我们直接进入编码。我使用 Visual Studio .NET 2003 创建一个 ASP.NET Web 应用程序,并将一个 DataGrid
控件添加到 WebForm(如果您没有在您的机器上安装 Visual Studio .NET 2003,请不要担心,只需创建一个 .aspx 页面并按照后面部分的描述操作代码,但我强烈建议使用代码隐藏文件,以便代码易于理解并从逻辑上与演示文稿分开)。
首先,我们声明一个 DataGrid
控件实例
protected System.Web.UI.WebControls.DataGrid dgItems;
接下来是 Page_Load
事件处理程序
private void Page_Load(object sender, System.EventArgs e)
{
this.dgItems.ItemCreated +=
new DataGridItemEventHandler(dgItems_ItemCreated);
在这里,我们附加 DataGrid
的 ItemCreated
事件。实际上,此事件使我们可以在创建 DataGrid
时访问其中的每一行。 我们利用这一点并使用此事件来访问包含分页器的行。
//Declare and intialize ArrayList
ArrayList arrLst = new ArrayList();
//Simply add Numbers from 1 - 50 to the ArrayList
for(Int32 count = 1; count <= 50 ; count++)
{
arrLst.Add(count.ToString());
}//end for
创建一个 ArrayList
,arrLst
,并将从 1 到 50 的数字添加到其中。 稍后,我们使用 arrLst
作为 DataGrid
的 DataSource
。 顺便说一句,如果您觉得将 ArrayList
设置为数据源很奇怪,请不要这样想,因为 DataGrid
控件可以绑定到任何实现 IEnumerable
接口的类型。 这样,您可以将 HashTable
、Dictionary
、Array
或 Stack
用作 DataGrid
的数据源。
继续处理代码片段
//Set datasource of datagrid to arraylist
this.dgItems.DataSource = arrLst;
/Enable Paging , so that we can perform custom styles on it
this.dgItems.AllowPaging = true;
//Set the item Limits for a single page
this.dgItems.PageSize = 10 ;
//Specify Paging Style
this.dgItems.PagerStyle.Mode = PagerMode.NumericPages;
//Finally Bind the data
this.dgItems.DataBind();
代码非常容易解释。 首先,将 DataGrid
控件的 DataSource
设置为我们创建的 ArrayList
arrLst
。 我还允许分页,因此设置页面大小,将 pagerStyle
的模式设置为 Numeric
(可以更改),最后通过调用 DataBind()
方法将数据绑定到 DataGrid
dgItems
。
查看 Item_Created
事件处理程序
private void dgItems_ItemCreated(object sender, DataGridItemEventArgs e)
if ( e.Item.ItemType == ListItemType.Pager)
{
在这里,我们从检查开始。 就目前而言,我们只对包含分页器的行感兴趣。 所以我们必须首先检查它。 我们通过检查当前 Item
的 ItemType
来完成,它可以是 Pager
、Header
、Footer
等。我们检查 Pager
。 如您所见,我们借助 ListItemType
枚举器,可以轻松检查所需的类型。
//Add a new Label Control
Label lblPagerText = new Label();
lblPagerText.Text = " | Pages --> " ;
lblPagerText.Font.Bold = true;
接下来,我们创建一个新的 Label
控件 lblPagerText
。 我们将使用此 lblPagerText
在该行的最左角显示文本。 我们设置 lblPagerText
的 Text
属性,并通过将 Bold
属性设置为 true
使其加粗。
虽然我在这里使用 Label
控件,但是一旦掌握了诀窍,可能性是无限的。 例如,您可能需要一个超链接,单击它会显示详细信息。
if ( e.Item.Controls[0].FindControl("lblPagerText1" ) == null)
接下来,我们进行检查,以确认我们的 Label
控件 lblPagerText1
尚未添加到控件中。 如果我们删除此检查,则将多次添加该控件。
e.Item.Controls[0].Controls.AddAt(0,lblPagerText);
最后,我们将 Label
添加到 Controls
集合。 让我详细解释一下。 第一项,Controls[0]
,返回一个 TableCell
控件。 此表单元格包含所有分页链接。 现在,由于我们希望将文本插入到该行的开头,因此我们必须使用 Controls
集合的 AddAt
方法并通过使用索引 0 强制将我们的控件添加为第一个控件,将其添加到 Controls
集合的开头。
现在编译代码并运行它。 如果您使用的是文章中附带的示例解决方案,只需运行 GridProj EXE。
结论
在这里,我们看到了如何在 DataGrid
上显示分页器的行开头插入文本。 在以后的文章中,我将向您展示如何摆脱数字分页并放置我们自己的分页字符,例如字母,并使它们像普通分页链接一样工作。 现在,再见,祝您编程愉快!