ASP.NET DataPager Control in a Server Control
I'm trying to create a Server Control that will use a DataPager Control, but I'm having some difficulties with the PagerTemplate.
This is the DataPager control that I want to generate from a Server Control:
<asp:DataPager ID="myPager" PageSize="20" runat="server">
<Fields>
<asp:TemplatePagerField>
<PagerTemplate>
<div class="counter">
<%# Container.StartRowIndex + 1 %> to
<%# ((Container.StartRowIndex + Container.PageSize) > Container.TotalRowCount ? Con开发者_如何学运维tainer.TotalRowCount : (Container.StartRowIndex + Container.PageSize)) %>
of <%# Container.TotalRowCount %> records
</div>
</PagerTemplate>
</asp:TemplatePagerField>
<asp:NextPreviousPagerField ButtonType="link"
FirstPageText="first"
ShowFirstPageButton="true"
ShowNextPageButton="false"
ShowPreviousPageButton="false"
RenderDisabledButtonsAsLabels="true" />
<asp:NumericPagerField ButtonCount="7" />
<asp:NextPreviousPagerField ButtonType="link"
LastPageText="last"
ShowLastPageButton="true"
ShowNextPageButton="false"
ShowPreviousPageButton="false" />
</Fields>
</asp:DataPager>
I don't know how to create the PagerTemplate from code. I'm stuck in a part where I need to create a ITemplate, but I don't know how to work with it.
I've done some search but haven't found anything that could help me. I'm a bit newbie with Server Controls. I can do some simple ones, but templates are new to me.
Can anyone give me some help on this?
Thanks :)
You need to create a class that implements ITemplate in order to set a template field programmatically. Here is an example:
/// <summary>
/// A template that goes within a data pager template field to display record count information.
/// </summary>
internal class RecordTemplate : ITemplate
{
/// <summary>
/// Instantiates this template within a parent control.
/// </summary>
/// <param name="container"></param>
public void InstantiateIn(Control container)
{
DataPager pager = container.NamingContainer as DataPager;
if (pager != null)
{
pager.Controls.Add(new Literal()
{
Text = String.Format("Showing records {0} to {1} of {2}",
pager.StartRowIndex + 1,
Math.Min(pager.StartRowIndex + pager.PageSize, pager.TotalRowCount),
pager.TotalRowCount)
});
}
}
}
Then in your server control code where you are creating the DataPager you can do the following:
TemplatePagerField field = new TemplatePagerField();
field.PagerTemplate = new RecordTemplate();
MyDataPager.Fields.Add(field);
精彩评论