(); categoryList.Add(new Category { ID = 0, Name = "All" });
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ConnectionString);
string sql = "SELECT * FROM Category";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Category category = new Category();
category.ID = Convert.ToInt32(dr["ID"]);
category.Name = dr["Name"].ToString();
categoryList.Add(category);
}
conn.Close();
ddlCategory.DataSource = categoryList;
ddlCategory.DataTextField = "Name";
ddlCategory.DataValueField = "ID";
ddlCategory.DataBind();
}
protected void BindData()
{
int pageIndex = AspNetPager1.CurrentPageIndex - 1;
int pageSize = AspNetPager1.PageSize;
string categoryID = ddlCategory.SelectedValue;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ConnectionString);
string sql = "SELECT a.ID, a.Title, a.Content, a.CreateTime, b.Name AS CName FROM News a LEFT JOIN Category b ON a.CategoryId=b.ID";
if (categoryID != "0")
{
sql += " WHERE a.CategoryId=" + categoryID;
}
sql += " ORDER BY CreateTime DESC OFFSET " + pageIndex * pageSize + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
List newsList = new List(); while (dr.Read())
{
News news = new News();
news.ID = Convert.ToInt32(dr["ID"]);
news.Title = dr["Title"].ToString();
news.Content = dr["Content"].ToString();
news.CreateTime = Convert.ToDateTime(dr["CreateTime"]);
news.CategoryName = dr["CName"].ToString();
newsList.Add(news);
}
conn.Close();
gvNews.DataSource = newsList;
gvNews.DataBind();
sql = "SELECT COUNT(*) FROM News";
if (categoryID != "0")
{
sql += " WHERE CategoryId=" + categoryID;
}
cmd = new SqlCommand(sql, conn);
conn.Open();
AspNetPager1.RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
AspNetPager1.DataBind();
conn.Close();
}
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
BindData();
}
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
{
BindData();
}
}
四、总结
AspNetPager是一个非常方便的ASP.NET分页控件,可以轻松地实现在ASP.NET网站中显示数据列表和分页功能。它提供了大量的属性和方法,可以满足大多数分页需求。在使用AspNetPager时,只需按照固定的步骤进行设置即可。本文提供了一些简单的示例代码,希望读者可以掌握AspNetPager的使用。 如果你喜欢我们三七知识分享网站的文章,
欢迎您分享或收藏知识分享网站文章
欢迎您到我们的网站逛逛喔!https://www.37seo.cn/
发表评论 取消回复