gridview 编辑,删除,更新的用法

本文介绍了一个使用ASP.NET的GridView控件实现数据展示、分页、编辑、更新及删除功能的完整示例。通过该示例可以了解如何利用ASP.NET Web Forms中的GridView进行数据操作。
ContractedBlock.gifExpandedBlockStart.gifCode
  1<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewUp.aspx.cs" Inherits="gridview_GridViewUp" %>
  2
  3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4<html xmlns="http://www.w3.org/1999/xhtml">
  5<head runat="server">
  6    <title>无标题页</title>
  7</head>
  8<body>
  9    <form id="form1" runat="server">
 10        <div>
 11            <table cellpadding="0" cellspacing="0" border="0" width="80%" style="font-size: 11px">
 12                <tr>
 13                    <td align="center">
 14                        <asp:GridView ID="GridView1" runat="server" Width="100%" CellPadding="4" ForeColor="#333333"
 15                            AutoGenerateColumns="False" AllowPaging="True" PageSize="12" OnRowCancelingEdit="GridView1_RowCancelingEdit"
 16                            OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting"
 17                            DataKeyNames="id,name" OnPageIndexChanging="GridView1_PageIndexChanging" DataMember="card,price" OnRowDataBound="GridView1_RowDataBound" GridLines="None">
 18                            <Columns>
 19                                <asp:BoundField HeaderText="身份证号" DataField="card" Visible=false />
 20                                <asp:BoundField HeaderText="编号" DataField="id" ReadOnly="True" />
 21                                <asp:BoundField DataField="name" HeaderText="姓名" ReadOnly="True" />
 22                                <asp:TemplateField HeaderText="身份证号">
 23                                    <ItemTemplate>
 24                                        <%# Eval("card"%>
 25                                    </ItemTemplate>
 26                                    <EditItemTemplate>
 27                                        <asp:TextBox ID="TBCard" Text='<%# Eval("card") %>' runat="server" Width="140px" />
 28                                    </EditItemTemplate>
 29                                    <ItemStyle Width="150px" />
 30                                </asp:TemplateField>
 31                                <asp:TemplateField HeaderText="学历">
 32                                    <ItemTemplate>
 33                                        <%# Eval("description")%>
 34                                    </ItemTemplate>
 35                                    <EditItemTemplate>
 36                                        <asp:HiddenField ID="HDFXueli" runat="server" Value='<%# Eval("xueli") %>' />
 37                                        <asp:DropDownList ID="DDLXueli" runat="server" Width="90px" />
 38                                    </EditItemTemplate>
 39                                    <ItemStyle Width="100px" />
 40                                </asp:TemplateField>
 41                                <asp:TemplateField HeaderText="价格">
 42                                    <ItemTemplate>
 43                                        <%# Eval("price"%>
 44                                    </ItemTemplate>
 45                                    <EditItemTemplate>
 46                                        <asp:TextBox ID="TBPrice" Text='<%# Eval("price") %>' runat="server" Width="90px" />
 47                                    </EditItemTemplate>
 48                                    <ItemStyle Width="100px" />
 49                                </asp:TemplateField>
 50                                <asp:BoundField HeaderText="建立时间" DataField="createdate" ReadOnly="True" />
 51                                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" HeaderText="操作" />
 52                            </Columns>
 53                            <PagerSettings FirstPageText="" LastPageText="" NextPageText="" PreviousPageText="" />
 54                            <RowStyle Height="20px" BackColor="#F7F6F3" ForeColor="#333333" />
 55                            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
 56                            <EditRowStyle BackColor="#999999" />
 57                            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
 58                            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
 59                            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
 60                            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
 61                        </asp:GridView>
 62                    </td>
 63                </tr>
 64            </table>
 65        </div>
 66    </form>
 67</body>
 68</html>
 69
 70GridViewUp.aspx.cs文件代码:
 71using System;
 72using System.Data;
 73using System.Configuration;
 74using System.Collections;
 75using System.Web;
 76using System.Web.Security;
 77using System.Web.UI;
 78using System.Web.UI.WebControls;
 79using System.Web.UI.WebControls.WebParts;
 80using System.Web.UI.HtmlControls;
 81using System.Data.SqlClient;
 82
 83public partial class gridview_GridViewUp : System.Web.UI.Page
 84ExpandedBlockStart.gifContractedBlock.gif{
 85    protected void Page_Load(object sender, EventArgs e)
 86ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 87        if (!IsPostBack)
 88ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 89            GridViewBind();
 90        }

 91    }

 92
 93    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
 94ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 95        GridView1.PageIndex = e.NewPageIndex;
 96        GridViewBind();
 97    }

 98
 99    private void GridViewBind()
100ExpandedSubBlockStart.gifContractedSubBlock.gif    {
101        string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
102        string SqlStr = "Select a.*,b.description FROM test01 a,xueli b where a.xueli=b.code and a.id<1000 and a.id>200";
103        DataSet ds = new DataSet();
104
105        try
106ExpandedSubBlockStart.gifContractedSubBlock.gif        {
107            SqlConnection conn = new SqlConnection(connStr);
108            if (conn.State.ToString() == "Closed") conn.Open();
109            SqlDataAdapter da = new SqlDataAdapter(SqlStr, conn);
110            da.Fill(ds, "test01");
111            if (conn.State.ToString() == "Open") conn.Close();
112
113            GridView1.DataSource = ds.Tables[0].DefaultView;
114            GridView1.DataBind();
115        }

116        catch (Exception ex)
117ExpandedSubBlockStart.gifContractedSubBlock.gif        {
118            Response.Write("数据库错误,错误原因:" + ex.Message);
119            Response.End();
120        }

121    }

122
123    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
124ExpandedSubBlockStart.gifContractedSubBlock.gif    {
125        if (((DropDownList)e.Row.FindControl("DDLXueli")) != null)
126ExpandedSubBlockStart.gifContractedSubBlock.gif        {        
127            DropDownList ddlxueli = (DropDownList)e.Row.FindControl("DDLXueli");
128
129            // 生成 DropDownList 的值,绑定数据
130            string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
131            string SqlStr = "Select * from xueli";
132            DataSet ds = new DataSet();
133
134            SqlConnection conn = new SqlConnection(connStr);
135            if (conn.State.ToString() == "Closed") conn.Open();
136            SqlDataAdapter da = new SqlDataAdapter(SqlStr, conn);
137            da.Fill(ds, "xueli");
138            if (conn.State.ToString() == "Open") conn.Close();
139
140            ddlxueli.DataSource = ds.Tables[0].DefaultView;
141            ddlxueli.DataTextField = "description";
142            ddlxueli.DataValueField = "code";
143            ddlxueli.DataBind();
144            //
145
146            // 选中 DropDownList
147            ddlxueli.SelectedValue = ((HiddenField)e.Row.FindControl("HDFXueli")).Value;
148            //
149        }

150    }

151
152    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
153ExpandedSubBlockStart.gifContractedSubBlock.gif    {
154        GridView1.EditIndex = e.NewEditIndex;
155        GridViewBind();
156    }

157    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
158ExpandedSubBlockStart.gifContractedSubBlock.gif    {
159        GridView1.EditIndex = -1;
160        GridViewBind();
161    }

162
163    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
164ExpandedSubBlockStart.gifContractedSubBlock.gif    {
165        string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
166        string card = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TBCard")).Text;
167        string xueli = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("DDLXueli")).SelectedValue;
168        string price = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TBPrice")).Text;
169
170        string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
171        string SqlStr = "update test01 set card='" + card + "',xueli='" + xueli + "',price='" + price + "' where id=" + id;
172
173        try
174ExpandedSubBlockStart.gifContractedSubBlock.gif        {
175            SqlConnection conn = new SqlConnection(connStr);
176            if (conn.State.ToString() == "Closed") conn.Open();
177            SqlCommand comm = new SqlCommand(SqlStr, conn);
178            comm.ExecuteNonQuery();
179            comm.Dispose();
180            if (conn.State.ToString() == "Open") conn.Close();
181
182            GridView1.EditIndex = -1;
183            GridViewBind();
184        }

185        catch (Exception ex)
186ExpandedSubBlockStart.gifContractedSubBlock.gif        {
187            Response.Write("数据库错误,错误原因:" + ex.Message);
188            Response.End();
189        }

190    }

191
192    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
193ExpandedSubBlockStart.gifContractedSubBlock.gif    {
194        string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
195        string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
196        string SqlStr = "delete from test01 where id=" + id;
197
198        try
199ExpandedSubBlockStart.gifContractedSubBlock.gif        {
200            SqlConnection conn = new SqlConnection(connStr);
201            if (conn.State.ToString() == "Closed") conn.Open();
202            SqlCommand comm = new SqlCommand(SqlStr, conn);
203            comm.ExecuteNonQuery();
204            comm.Dispose();
205            if (conn.State.ToString() == "Open") conn.Close();
206
207            GridView1.EditIndex = -1;
208            GridViewBind();
209        }

210        catch (Exception ex)
211ExpandedSubBlockStart.gifContractedSubBlock.gif        {
212            Response.Write("数据库错误,错误原因:" + ex.Message);
213            Response.End();
214        }

215    }

216}

217
218sql server2000生成表代码:
219Create TABLE [dbo].[test01] (
220    [id] [decimal](180) IDENTITY (11) NOT NULL ,
221    [name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
222    [card] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
223    [xueli] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
224    [price] [decimal](180) NULL ,
225    [createdate] [datetime] NULL 
226) ON [PRIMARY]
227GO
228
229Alter TABLE [dbo].[test01] ADD 
230    CONSTRAINT [DF_test01_createdate] DEFAULT (getdate()) FOR [createdate],
231    CONSTRAINT [PK_test01] PRIMARY KEY CLUSTERED 
232    (
233        [id]
234    ) ON [PRIMARY] 
235GO
236
237
238Create TABLE [dbo].[xueli](
239    [id] [int] IDENTITY(1,1) NOT NULL,
240    [code] [int] NULL,
241    [description] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
242CONSTRAINT [PK_xueli] PRIMARY KEY CLUSTERED 
243(
244    [id] ASC
245)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
246) ON [PRIMARY] 
247
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值