我有网格视图,我在其中添加了属性允许排序,我将网格视图中的所有字段转换为项目模板,然后出现此错误(GridView'GridView1'触发了未处理的事件排序) 请有人帮帮我
“> “> “> “> “> “> “> “> “> “> “> “> “> “>
答案 0 :(得分:0)
如果您没有将GridView绑定到SqlDataSource并且将其AllowSorting设置为true,则需要手动进行排序。您需要将排序事件分配给GridView,并编写自己的代码以实现排序。您可以参考下面的代码,并进行相应的修改。
在aspx页面上:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
onsorting="GridView1_Sorting">
</asp:GridView>
关于代码隐藏:
public partial class GridViewSort : System.Web.UI.Page
{
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
GridView1.DataSource = GetStaff();
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
DataTable dt = GetStaff();
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
/// <summary>
/// Dummy data
/// </summary>
/// <returns></returns>
private DataTable GetStaff()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
for (int i = 1; i <= 20; i++)
{
dt.Rows.Add(i, "Staff - " + i, 20 );
}
return dt;
}
}