下面我会详细讲解如何在 ASP.NET 中使用 GridView 控件实现数据的查询、分页、编辑更新和删除操作。
1. GridView 的基本使用
GridView 控件是 ASP.NET 中用于展示数据的常用控件之一,通常用于展示数据列表。它可以从数据源中获取数据并将数据呈现为表格形式,在网页中显示出来。GridView 控件支持分页、排序和编辑更新等功能。它的基本语法如下:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" />
<asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete" />
</Columns>
</asp:GridView>
其中,AutoGenerateColumns="False"
表示关闭自动生成列的功能,数据列需要手动添加。DataKeyNames
表示指定数据绑定时使用的主键字段。数据列可以使用 BoundField 控件添加,按钮列可以使用 ButtonField 控件添加。
2. 数据绑定
GridView 控件支持多种数据源,如 SQL Server、Oracle、Access 和 XML 等。下面以 SQL Server 为例,演示如何绑定数据源。
2.1 配置连接字符串
在 web.config 文件中添加数据库连接字符串,内容如下:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=localhost;Initial Catalog=TestDB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
其中,ConnectionString
表示连接字符串的名称,Data Source
表示数据库服务器的名称,Initial Catalog
表示数据库的名称,Integrated Security
表示使用 Windows 身份验证方式。
2.2 添加数据源
在页面中添加 SqlDataSource 控件用于绑定数据源,内容如下:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Age] FROM [UserInfo]">
</asp:SqlDataSource>
其中,ConnectionString
属性表示连接字符串名称,SelectCommand
属性表示 SQL 查询语句。
2.3 绑定数据
将 GridView 控件和数据源绑定在一起,实现数据的展示。代码如下:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" />
<asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete" />
</Columns>
</asp:GridView>
其中,DataSourceID
属性表示指定数据源控件的 ID。
3. GridView 的分页
GridView 控件内置了分页功能,可以使用 PagerTemplate 控件指定分页模板,并设置其分页方式。分页方式包括:自动分页和手动分页两种。
3.1 自动分页
使用自动分页可以设置分页的页面大小,GridView 控件会自动根据页面大小分页。示例代码如下:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" PageSize="5">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" />
<asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete" />
</Columns>
<PagerSettings Mode="NumericFirstLast" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Center" />
</asp:GridView>
其中,PageSize
属性表示每页显示的记录数,PagerSettings
和 PagerStyle
分别指定分页样式和分页控件的设置。
3.2 手动分页
使用手动分页需要在代码中实现分页功能,示例代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "SELECT COUNT(ID) FROM UserInfo";
SqlCommand cmd = new SqlCommand(sql, conn);
int count = (int)cmd.ExecuteScalar();
int pageSize = 5;
int pageNum = (int)Math.Ceiling((double)count / pageSize);
ViewState["PageNum"] = pageNum;
ViewState["PageIndex"] = 1;
BindPage();
BindGridView();
}
}
private void BindPage()
{
int pageNum = (int)ViewState["PageNum"];
int pageIndex = (int)ViewState["PageIndex"];
StringBuilder sb = new StringBuilder();
sb.Append("<div>");
for (int i = 1; i <= pageNum; i++)
{
if (i == pageIndex)
sb.Append("<span>" + i + "</span>");
else
sb.Append("<a href='#' onclick='gotoPage(" + i + ")'>" + i + "</a>");
}
sb.Append("</div>");
Literal1.Text = sb.ToString();
}
private void BindGridView()
{
int pageSize = 5;
int pageIndex = (int)ViewState["PageIndex"];
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "SELECT TOP " + pageSize + " * FROM (SELECT ROW_NUMBER() OVER (ORDER BY ID DESC) AS RowNumber,ID,Name,Age FROM UserInfo) AS T WHERE RowNumber > " + (pageIndex - 1) * pageSize + " ORDER BY ID DESC";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = (int)GridView1.DataKeys[e.RowIndex].Value;
string name = e.NewValues["Name"].ToString();
int age = int.Parse(e.NewValues["Age"].ToString());
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "UPDATE UserInfo SET Name=@Name, Age=@Age WHERE ID=@ID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Age", age);
cmd.Parameters.AddWithValue("@ID", id);
cmd.ExecuteNonQuery();
}
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = (int)GridView1.DataKeys[e.RowIndex].Value;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "DELETE FROM UserInfo WHERE ID=@ID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@ID", id);
cmd.ExecuteNonQuery();
}
GridView1.EditIndex = -1;
BindGridView();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
int pageIndex = (int)ViewState["PageIndex"];
if (pageIndex > 1)
{
ViewState["PageIndex"] = pageIndex - 1;
BindPage();
BindGridView();
}
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
int pageIndex = (int)ViewState["PageIndex"];
int pageNum = (int)ViewState["PageNum"];
if (pageIndex < pageNum)
{
ViewState["PageIndex"] = pageIndex + 1;
BindPage();
BindGridView();
}
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
int pageNum = (int)ViewState["PageNum"];
ViewState["PageIndex"] = pageNum;
BindPage();
BindGridView();
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
ViewState["PageIndex"] = 1;
BindPage();
BindGridView();
}
手动分页涉及到页面大小、总记录数、总页数、当前页码和分页控件等多个变量,需要在代码中进行维护,比较麻烦。此外,还需要为分页控件添加事件以实现分页的操作。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:asp.net中gridview的查询、分页、编辑更新、删除的实例代码 - Python技术站