带有分页器 TopAndBottom 的 GridView [英] GridView with Pager TopAndBottom
问题描述
我已经扩展了 ASP.NET 中的标准 GridView 控件.基本上是一样的,但是分页和排序是使用回调完成的.
我已经成功创建了自己的 PagerTemplate,但它仅在 PagerSettings.Position 设置为 Top 时才有效.我想在顶部和底部都有寻呼机.
我收到一个 HttpException 说:表格必须包含按页眉、正文、页脚顺序排列的行部分.
有人知道这是什么吗?
我已经尝试调用 MakeAccessible() 方法,但这没有帮助.
代码:
private int _IdColumnIndex = -1;公共覆盖对象数据源{得到{返回 HttpContext.Current.Session[this.ClientID + "_DataSource"];}放{如果 (!value.GetType().Equals(typeof(DataView)))throw new ArgumentException("只接受 System.Data.DataView 作为 DataGridView 的数据源!");HttpContext.Current.Session[this.ClientID + "_DataSource"] = value;}}///<总结>///设置默认设置.///</总结>私有无效 SetDefaultSettings(){base.AllowPaging = true;base.AllowSorting = true;base.ShowHeader = true;base.ShowFooter = true;base.PagerTemplate = new GridPagerTemplate(PAGER_ID, this);base.PagerSettings.Position = PagerPosition.TopAndBottom;base.PageSize = 10;添加选择复选框();}//私有无效MakeAccessible()//{//如果 (this.Rows.Count > 0)//{////这将替换<td>与 <th>并添加范围属性//this.UseAccessibleHeader = true;////这将添加<thead>和 <tbody>元素//this.HeaderRow.TableSection = TableRowSection.TableHeader;////这会添加<tfoot>元素.如果没有页脚行,请删除//this.FooterRow.TableSection = TableRowSection.TableFooter;//}//}私有无效 AddSelectionCheckbox(){TemplateField tf = new TemplateField();tf.HeaderText = "";tf.ItemTemplate = new CheckboxTemplate(ROW_CHECKBOX_ID);base.Columns.Add(tf);}protected override void OnInit(EventArgs e){设置默认设置();base.DataBound += new EventHandler(DataGridView_DataBound);base.RowDataBound += new GridViewRowEventHandler(DataGridView_RowDataBound);base.OnInit(e);}protected override void OnPreRender(EventArgs e){base.OnPreRender(e);//this.PaintRows();//this.FormatCells();//获取此 DataGridView 的 JavaScript,并将其包含在页面中.string scriptUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "Yakinix.UI.Controls.DataGridView.js");Page.ClientScript.RegisterClientScriptInclude("DataGridView", scriptUrl);string js = "函数 DGV_MakeCallback(参数)" +"{" +__theFormPostData = '';"+__theFormPostCollection = new Array();"+WebForm_InitCallback();"+GetCallbackEventReference("DGV_Callback") +";}";Page.ClientScript.RegisterClientScriptBlock(typeof(DataGridView), typeof(DataGridView).FullName + "DGV_MakeCallback", js, true);如果 (this.HeaderRow != null)this.HeaderRow.TableSection = TableRowSection.TableHeader;}私有字符串 GetCallbackEventReference(string func){string callbackEventReference = Page.ClientScript.GetCallbackEventReference(this, "argument", func, "'" + ClientID + "'", false);返回回调事件引用;}公共覆盖无效 RenderBeginTag(HtmlTextWriter writer){writer.RenderBeginTag(HtmlTextWriterTag.Div);//base.RenderBeginTag(writer);}公共覆盖无效 RenderEndTag(HtmlTextWriter writer){base.RenderEndTag(writer);writer.RenderEndTag();//}///<总结>///渲染 gridview 控件并去除空白.它也是///应用正确的格式.///</总结>公共字符串 RenderHtml(){使用 (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)){//this.PaintRows();//this.FormatCells();如果 (this.HeaderRow != null)this.HeaderRow.TableSection = TableRowSection.TableHeader;this.UseAccessibleHeader = true;this.RenderControl(new HtmlTextWriter(sw));字符串 html = sw.ToString();返回html;}}//TODO:为与当前 SortExpression 匹配的列设置所有行的样式.protected void DataGridView_RowDataBound(object sender, GridViewRowEventArgs e){//DataGridView gridView = (DataGridView)sender;//如果(gridView.SortExpression.Length > 0)//{//int cellIndex = -1;////找到对应排序表达式的列索引//foreach(gridView.Columns 中的DataControlField 字段)//{//if (field.SortExpression == gridView.SortExpression)//{//cellIndex = gridView.Columns.IndexOf(field);// 休息;//}//}//如果(单元格索引 > -1)//{//if (e.Row.RowType == DataControlRowType.Header)//{////这是一个标题行,////设置排序方式//e.Row.Cells[cellIndex].CssClass += (gridView.SortDirection == SortDirection.Ascending ? " sortascheader" : " sortdescheader");//}//else if (e.Row.RowType == DataControlRowType.DataRow)//{////这是一个数据行//e.Row.Cells[cellIndex].CssClass += (e.Row.RowIndex % 2 == 0 ? " sortaltrow" : "sortrow");//}//}//}RenderDetailsRow(e);}///<总结>///渲染细节行,渲染时隐藏.单击详细信息链接,显示行并显示更详细的数据,并且可以编辑.///</总结>///<param name="e">Edit";}}公共覆盖无效排序(字符串 sortExpression,SortDirection sortDirection){DataView dv = this.DataSource as DataView;如果(dv != 空){dv.Sort = sortExpression + " " + (sortDirection == SortDirection.Ascending ? "ASC" : "DESC");}}#region ICallbackEventHandler 成员私有字符串 callbackArg = String.Empty;字符串 ICallbackEventHandler.GetCallbackResult(){//使用 PageStatePersister 保存状态并将其放置到 Page.ClientStateSystem.Reflection.MethodInfo mi = typeof(Page).GetMethod("SaveAllState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);mi.Invoke(this.Page, null);//从 Page 的 ClientState 获取序列化的视图状态System.Reflection.PropertyInfo stateProp = typeof(Page).GetProperty("ClientState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);string state = stateProp.GetValue(this.Page, null).ToString();return callbackArg + "¤#¤" + state;}void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument){尝试{//从客户端加载 XMLXmlDocument doc = new XmlDocument();doc.LoadXml(eventArgument.Replace("&", "&"));字符串 pagerId = String.Empty;if (doc.DocumentElement.Name == "回调"){字符串 gridId = doc.DocumentElement["arguments"]["gridId"].InnerText;开关 (doc.DocumentElement["action"].InnerText){案例排序":字符串 sortExpression = doc.DocumentElement["arguments"]["sortExpression"].InnerText;Sort(sortExpression.Split(' ')[0].Trim(), sortExpression.Split(' ')[1].Trim().Equals("ASC") ? SortDirection.Ascending : SortDirection.Descending);休息;案例页面":字符串 pageIndex = doc.DocumentElement["arguments"]["pageIndex"].InnerText;this.PageIndex = Convert.ToInt32(pageIndex);pagerId = base.BottomPagerRow.Cells[0].FindControl(PAGER_ID).ClientID;休息;案例搜索":休息;}this.DataBind();callbackArg = String.Format("{0}¤|¤{1}¤|¤{2}", gridId, this.RenderHtml(), pagerId);}文档 = 空;}捕获(异常前){callbackArg = String.Format(AJAX_ERROR_FORMAT, ex.Message + "
" + ex.StackTrace);}最后{if (callbackArg.Equals(string.Empty)){callbackArg = String.Format(AJAX_ERROR_FORMAT, "发生 AJAX 错误!");}}}#endregion
这对我有用.必须将 PagerRows 设置为适当的部分.
我从http://www.codeproject.com/Members/iguigova?msg=3153516(搜索 MakeAccessible)
protected override void OnPreRender(EventArgs e){base.OnPreRender(e);如果 (Rows.Count > 0){UseAccessibleHeader = true;HeaderRow.TableSection = TableRowSection.TableHeader;FooterRow.TableSection = TableRowSection.TableFooter;}如果(TopPagerRow != null){TopPagerRow.TableSection = TableRowSection.TableHeader;}if (BottomPagerRow != null){BottomPagerRow.TableSection = TableRowSection.TableFooter;}}
I have extended the standard GridView control in ASP.NET. Basically it is just the same, but paging and sorting is done using callbacks.
I have successfully created my own PagerTemplate, but it only works when PagerSettings.Position is set to Top. I want to have the pager at both the top and the bottom.
I get an HttpException saying: The table must contain row sections in order of header, body, then footer.
Anyone know what this could be?
I already tried calling the MakeAccessible() method, but that doesn't help.
Code:
private int _IdColumnIndex = -1;
public override object DataSource
{
get
{
return HttpContext.Current.Session[this.ClientID + "_DataSource"];
}
set
{
if (!value.GetType().Equals(typeof(DataView)))
throw new ArgumentException("Only System.Data.DataView is accepted as a DataSource for DataGridView!");
HttpContext.Current.Session[this.ClientID + "_DataSource"] = value;
}
}
/// <summary>
/// Sets the default settings.
/// </summary>
private void SetDefaultSettings()
{
base.AllowPaging = true;
base.AllowSorting = true;
base.ShowHeader = true;
base.ShowFooter = true;
base.PagerTemplate = new GridPagerTemplate(PAGER_ID, this);
base.PagerSettings.Position = PagerPosition.TopAndBottom;
base.PageSize = 10;
AddSelectionCheckbox();
}
//private void MakeAccessible()
//{
// if (this.Rows.Count > 0)
// {
// //This replaces <td> with <th> and adds the scope attribute
// this.UseAccessibleHeader = true;
// //This will add the <thead> and <tbody> elements
// this.HeaderRow.TableSection = TableRowSection.TableHeader;
// //This adds the <tfoot> element. Remove if you don't have a footer row
// this.FooterRow.TableSection = TableRowSection.TableFooter;
// }
//}
private void AddSelectionCheckbox()
{
TemplateField tf = new TemplateField();
tf.HeaderText = "";
tf.ItemTemplate = new CheckboxTemplate(ROW_CHECKBOX_ID);
base.Columns.Add(tf);
}
protected override void OnInit(EventArgs e)
{
SetDefaultSettings();
base.DataBound += new EventHandler(DataGridView_DataBound);
base.RowDataBound += new GridViewRowEventHandler(DataGridView_RowDataBound);
base.OnInit(e);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
//this.PaintRows();
//this.FormatCells();
// Get JavaScript for this DataGridView, and include it on the page.
string scriptUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "Yakinix.UI.Controls.DataGridView.js");
Page.ClientScript.RegisterClientScriptInclude("DataGridView", scriptUrl);
string js = "function DGV_MakeCallback(argument)" +
"{" +
"__theFormPostData = '';" +
"__theFormPostCollection = new Array();" +
"WebForm_InitCallback();" +
GetCallbackEventReference("DGV_Callback") +
";}";
Page.ClientScript.RegisterClientScriptBlock(typeof(DataGridView), typeof(DataGridView).FullName + "DGV_MakeCallback", js, true);
if (this.HeaderRow != null)
this.HeaderRow.TableSection = TableRowSection.TableHeader;
}
private string GetCallbackEventReference(string func)
{
string callbackEventReference = Page.ClientScript.GetCallbackEventReference(this, "argument", func, "'" + ClientID + "'", false);
return callbackEventReference;
}
public override void RenderBeginTag(HtmlTextWriter writer)
{
writer.RenderBeginTag(HtmlTextWriterTag.Div); // <div>
base.RenderBeginTag(writer);
}
public override void RenderEndTag(HtmlTextWriter writer)
{
base.RenderEndTag(writer);
writer.RenderEndTag(); // </div>
}
/// <summary>
/// Renders the gridview control and strips whitespace. It also
/// applies the right formatting.
/// </summary>
public string RenderHtml()
{
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
{
//this.PaintRows();
//this.FormatCells();
if (this.HeaderRow != null)
this.HeaderRow.TableSection = TableRowSection.TableHeader;
this.UseAccessibleHeader = true;
this.RenderControl(new HtmlTextWriter(sw));
string html = sw.ToString();
return html;
}
}
// TODO: Style all rows for the column matching current SortExpression.
protected void DataGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
//DataGridView gridView = (DataGridView)sender;
//if (gridView.SortExpression.Length > 0)
//{
// int cellIndex = -1;
// // find the column index for the corresponding sort expression
// foreach (DataControlField field in gridView.Columns)
// {
// if (field.SortExpression == gridView.SortExpression)
// {
// cellIndex = gridView.Columns.IndexOf(field);
// break;
// }
// }
// if (cellIndex > -1)
// {
// if (e.Row.RowType == DataControlRowType.Header)
// {
// // this is a header row,
// // set the sort style
// e.Row.Cells[cellIndex].CssClass += (gridView.SortDirection == SortDirection.Ascending ? " sortascheader" : " sortdescheader");
// }
// else if (e.Row.RowType == DataControlRowType.DataRow)
// {
// // this is a data row
// e.Row.Cells[cellIndex].CssClass += (e.Row.RowIndex % 2 == 0 ? " sortaltrow" : "sortrow");
// }
// }
//}
RenderDetailsRow(e);
}
/// <summary>
/// Renders the details row, which is hidden when rendered. Clicking a details link, displays the row and more detailed data is shown, and is editable.
/// </summary>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
private void RenderDetailsRow(GridViewRowEventArgs e)
{
// Only add a details row to DataRows
if (false && e.Row.RowType == DataControlRowType.DataRow)
{
Table table = e.Row.Parent as Table;
if (table != null)
{
GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
row.Style[HtmlTextWriterStyle.Display] = "none";
TableCell rowCell = new TableCell();
rowCell.ColumnSpan = this.Columns.Count;
rowCell.Height = new Unit(100);
row.Cells.Add(rowCell);
table.Rows.Add(row);
HtmlAnchor htmlAhref = new HtmlAnchor();
htmlAhref.HRef = "javascript:void(0);";
htmlAhref.Attributes.Add("onclick", "ToggleElement('" + row.ClientID + "');");
htmlAhref.InnerText = "Test";
e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(htmlAhref);
}
}
}
protected void DataGridView_DataBound(object sender, EventArgs e)
{
FillPagerDetails(base.TopPagerRow);
FillPagerDetails(base.BottomPagerRow);
}
private void FillPagerDetails(GridViewRow pagerRow)
{
if (pagerRow != null)
{
// Retrieve the DropDownList and Label controls from the row.
DropDownList pageList = pagerRow.Cells[0].FindControl(PAGER_ID) as DropDownList;
if (pageList != null)
{
pageList.Attributes.Add("onchange", "DataGridViewPage(this.value, '" + ClientID + "');");
// Add the number of pages to the ListBox
for (int i = 0; i < base.PageCount; i++)
{
int pageNumber = i + 1;
// Create a ListItem that represents a page
ListItem item = new ListItem(String.Format("{0}", pageNumber), i.ToString());
// If the page is already selected, make sure the
// ListBox select the selected page
if (i == base.PageIndex)
item.Selected = true;
// Add the ListItem object to the Items collection of the DropDownList.
pageList.Items.Add(item);
}
}
}
}
protected override void InitializeRow(GridViewRow row, DataControlField[] fields)
{
base.InitializeRow(row, fields);
if (row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < row.Cells.Count; i++)
{
row.Cells[i].Controls.Clear();
if (row.Cells[i].Text.Equals("CHKCOL", StringComparison.Ordinal))
{
CheckBox chkSelectAll = new CheckBox();
chkSelectAll.ID = "chkSelectAllRows";
row.Cells[i].Controls.Add(chkSelectAll);
}
else
{
row.Cells[i].Text = String.Format(CultureInfo.InvariantCulture, "<a href="javaScript:DataGridViewSort('{0}', '{2}');void(0)" title="{1}">{1}</a>", fields[i].SortExpression, fields[i].HeaderText, this.ClientID);
}
}
//if (ViewState["SortExpression"] != null)
//{
// int index;
// index = 0;// GetHeaderCellIndex(ViewState["SortExpression"].ToString());
// if (index != -1)
// {
// //Literal literal;
// //if ((SortDirection)ViewState["SortDirection"] == SortDirection.Ascending)
// //{
// // if (string.IsNullOrEmpty(SortAscendingImageUrl))
// // {
// // literal = new Literal();
// // literal.Text = "↑";
// // row.Cells[index].Controls.Add(literal);
// // }
// // else
// // {
// // sortImage.ImageUrl = SortAscendingImageUrl;
// // row.Cells[index].Controls.Add(sortImage);
// // }
// //}
// //else
// //{
// // if (string.IsNullOrEmpty(SortDescendingImageUrl))
// // {
// // literal = new Literal();
// // literal.Text = "↓";
// // row.Cells[index].Controls.Add(literal);
// // }
// // else
// // {
// // sortImage.ImageUrl = SortDescendingImageUrl;
// // row.Cells[index].Controls.Add(sortImage);
// // }
// //}
// }
//}
}
else if (row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < row.Cells.Count; i++)
{
if (fields[i].HeaderText.Equals("id", StringComparison.InvariantCultureIgnoreCase))
{
_IdColumnIndex = i;
break;
}
}
}
}
protected override void OnRowCreated(GridViewRowEventArgs e)
{
base.OnRowCreated(e);
if (e.Row.RowType == DataControlRowType.Header)
{
//HtmlImage img = new HtmlImage();
//img.ID = "lbCheckAll";
//img.Src = "/img/btn_slct_all.gif";
//img.Alt = "Select all";
//img.Attributes.Add("onclick", "SelectAllRows('" + this.ClientID + "',true);return false;");
//e.Row.Cells[0].Controls.Add(img);
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
//AddCheckbox(e);
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
//e.Row.Cells[0].Text = "sdsds";
}
}
protected override void OnRowDataBound(GridViewRowEventArgs e)
{
base.OnRowDataBound(e);
if (e.Row.RowType == DataControlRowType.DataRow)
{
//AddCheckbox(e);
if (_IdColumnIndex != -1)
e.Row.Cells[_IdColumnIndex].Text = "<a href="Details.aspx?id=" + e.Row.Cells[_IdColumnIndex].Text + "">Edit</a>";
}
}
public override void Sort(string sortExpression, SortDirection sortDirection)
{
DataView dv = this.DataSource as DataView;
if (dv != null)
{
dv.Sort = sortExpression + " " + (sortDirection == SortDirection.Ascending ? "ASC" : "DESC");
}
}
#region ICallbackEventHandler Members
private string callbackArg = String.Empty;
string ICallbackEventHandler.GetCallbackResult()
{
// Save state with PageStatePersister and place it to Page.ClientState
System.Reflection.MethodInfo mi = typeof(Page).GetMethod("SaveAllState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
mi.Invoke(this.Page, null);
// Get serialized viewstate from Page's ClientState
System.Reflection.PropertyInfo stateProp = typeof(Page).GetProperty("ClientState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
string state = stateProp.GetValue(this.Page, null).ToString();
return callbackArg + "¤#¤" + state;
}
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
try
{
// Load XML from client
XmlDocument doc = new XmlDocument();
doc.LoadXml(eventArgument.Replace("&", "&"));
string pagerId = String.Empty;
if (doc.DocumentElement.Name == "callback")
{
string gridId = doc.DocumentElement["arguments"]["gridId"].InnerText;
switch (doc.DocumentElement["action"].InnerText)
{
case "sort":
string sortExpression = doc.DocumentElement["arguments"]["sortExpression"].InnerText;
Sort(sortExpression.Split(' ')[0].Trim(), sortExpression.Split(' ')[1].Trim().Equals("ASC") ? SortDirection.Ascending : SortDirection.Descending);
break;
case "page":
string pageIndex = doc.DocumentElement["arguments"]["pageIndex"].InnerText;
this.PageIndex = Convert.ToInt32(pageIndex);
pagerId = base.BottomPagerRow.Cells[0].FindControl(PAGER_ID).ClientID;
break;
case "search":
break;
}
this.DataBind();
callbackArg = String.Format("{0}¤|¤{1}¤|¤{2}", gridId, this.RenderHtml(), pagerId);
}
doc = null;
}
catch (Exception ex)
{
callbackArg = String.Format(AJAX_ERROR_FORMAT, ex.Message + "
" + ex.StackTrace);
}
finally
{
if (callbackArg.Equals(string.Empty))
{
callbackArg = String.Format(AJAX_ERROR_FORMAT, "An AJAX Error occurred!");
}
}
}
#endregion
This is what works for me.. the PagerRows must be set to their proper sections.
I got this tip from http://www.codeproject.com/Members/iguigova?msg=3153516 (search for MakeAccessible)
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Rows.Count > 0)
{
UseAccessibleHeader = true;
HeaderRow.TableSection = TableRowSection.TableHeader;
FooterRow.TableSection = TableRowSection.TableFooter;
}
if (TopPagerRow != null)
{
TopPagerRow.TableSection = TableRowSection.TableHeader;
}
if (BottomPagerRow != null)
{
BottomPagerRow.TableSection = TableRowSection.TableFooter;
}
}
这篇关于带有分页器 TopAndBottom 的 GridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!