通过使用示例代码作为指导,我设法将一些代码拼凑在一起,这些代码将在 gridview 上执行排序和分页。但是,我对网页编程比较陌生,所以我经常使用 ViewState(据我收集的资料来看,这很糟糕)。结果,我想知道是否有办法让我的代码更有效率?(或者完成同一件事的不同方式?)
前端:
<asp:GridView ID="UserAccounts" runat="server" AllowSorting="true" AutoGenerateColumns="false" AllowPaging="true"
OnSorting="gridView_Sorting" OnPageIndexChanging="gridView_PageIndexChanging" PageSize = "20">
<Columns>
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="Roles" HeaderText="Role" SortExpression="Roles" />
<asp:CheckBoxField DataField="IsLockedOut" HeaderText="Locked Out?" SortExpression="IsLockedOut" />
<asp:CheckBoxField DataField="IsOnline" HeaderText="Online?" SortExpression="IsOnline" />
<asp:BoundField DataField="LastLoginDate" HeaderText="Last Login Date" SortExpression="LastLoginDate" />
<asp:HyperLinkField Text="Manage" DataNavigateUrlFields="UserName" DataNavigateUrlFormatString="ManageDetails.aspx?user={0}" />
</Columns>
</asp:GridView>
生成表的代码后面:
private void BindUserAccounts()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserName");
dt.Columns.Add("Email");
dt.Columns.Add("Roles");
dt.Columns.Add("IsLockedOut");
dt.Columns.Add("IsOnline");
dt.Columns.Add("LastLoginDate");
var userRoles = from MembershipUser user in Membership.FindUsersByName(this.UsernameToMatch + "%")
let roles = Roles.GetRolesForUser(user.UserName)
select new
{
UserName = user.UserName,
Email = user.Email,
Roles = string.Join(", ", roles),
IsLockedOut = user.IsLockedOut,
IsOnline = user.IsOnline,
LastLoginDate = user.LastLoginDate
};
foreach (var u in userRoles)
{
DataRow dr = dt.NewRow();
dr["UserName"] = u.UserName;
dr["Email"] = u.Email;
dr["Roles"] = u.Roles;
dr["IsLockedOut"] = u.IsLockedOut;
dr["IsOnline"] = u.IsOnline;
dr["LastLoginDate"] = u.LastLoginDate;
dt.Rows.Add(dr);
}
UserAccounts.DataSource = dt;
UserAccounts.DataBind();
ViewState["DataSource"] = dt;
}
要启用排序和分页:
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
UserAccounts.PageIndex = e.NewPageIndex;
BindUserAccounts();
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = (DataTable)ViewState["DataSource"];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
if ((string)ViewState["SortDir"] == "ASC" || String.IsNullOrEmpty((string)ViewState["SortDir"]))
{
dataView.Sort = e.SortExpression + " ASC";
ViewState["SortDir"] = "DESC";
}
else if ((string)ViewState["SortDir"] == "DESC")
{
dataView.Sort = e.SortExpression + " DESC";
ViewState["SortDir"] = "ASC";
}
UserAccounts.DataSource = dataView;
UserAccounts.DataBind();
}
}