GridView使用案例

1.实现功能

使用GridView进行数据绑定分页显示,并进行数据的修改、删除等操作。

2.步骤

1).添加GridView控件,打开编辑列窗口,关闭自动生成字段,使用TemplateField手动添加字段,同时添加编辑、更新、取消和删除按钮;
2).设置GridView的DataKeyNames属性值,该值为某个字段名称,该属性可理解为每行的关键字段,在更新和删除时该属性值非常有用;
3).设置GridView控件各事件的处理程序,即在RowEditing、RowUpdating、RowDeleting、RowCancelingEdit、PageIndexChanging添加对应的处理函数名;
4).编写各事件处理程序;

3.示例代码

Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>GridView使用案例-Mzwu.Com</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            AllowPaging="True" DataKeyNames="ProductID"
            onpageindexchanging="GridView1_PageIndexChanging"
            onrowcancelingedit="GridView1_RowCancelingEdit"
            onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
            onrowupdating="GridView1_RowUpdating">
            <Columns>
                <asp:TemplateField HeaderText="ProductID">
                    <ItemTemplate>
                        <asp:Label ID="lblProductID" runat="server" Text='<%# Bind("ProductID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ProductName">
                    <ItemTemplate>
                        <asp:Label ID="lblProductName" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtProductName" runat="server" Text='<%# Bind("ProductName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemStyle Width="200px" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="CategoryID">
                    <ItemTemplate>
                        <asp:Label ID="lblCategoryID" runat="server" Text='<%# Bind("CategoryID") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtCategoryID" runat="server" Text='<%# Bind("CategoryID") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            DataBind();
    }

    protected void DataBind()
    {

        using (SqlConnection conn = new SqlConnection("server=(local);database=Northwind;user id=sa;password=sa;"))
        {
            using (SqlDataAdapter adapter = new SqlDataAdapter("Select * FROM Products orDER BY ProductID DESC", conn))
            {
                DataTable table = new DataTable();
                adapter.Fill(table);

                GridView1.DataSource = table;
                GridView1.DataBind();
            }
        }
            
    }
    
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        DataBind();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        using (SqlConnection conn = new SqlConnection("server=(local);database=Northwind;user id=sa;password=sa;"))
        {
            conn.Open();
            string productid = GridView1.DataKeys[e.RowIndex].Value + "";
            string productname = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtProductName")).Text;
            string sql = string.Format("Update Products SET ProductName='{0}' Where ProductID={1}", productname, productid);
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }

        GridView1.EditIndex = -1;
        DataBind();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        DataBind();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        using (SqlConnection conn = new SqlConnection("server=(local);database=Northwind;user id=sa;password=sa;"))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("Delete FROM Products Where ProductID=" + GridView1.DataKeys[e.RowIndex].Value, conn))
            {
                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }

        GridView1.EditIndex = -1;
        DataBind();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        DataBind();
    }
}


评论: 0 | 引用: 0 | 查看次数: 4552
发表评论
登录后再发表评论!