管志鹏的计算机主页

C# ASP.NET Java J2EE SSH SQL Server Oracle
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

GridView实现 "插入" 编辑更新删除功能

Posted on 2010-01-20 13:40  管志鹏  阅读(1702)  评论(7编辑  收藏  举报

     

老婆在项目中遇到了这样一个问题,要在显示的数据的下面实现插入功能,她刚接触.net开发,只好让我帮她实现,然后再教他了,以前都是在一个单独的页面中实现这种添加功能的,可是,这次是这样要求的,就从网上找了一下实现 方法,然后自己进行了总结,来记录一下,并不感觉这样实现方法特别好,不过,也纪念一下吧.

然后我在想,用Datalist或者Repeater是不是也能实现呢?等有时间,再学习一下

这里是一些关键代码,具体实现请下载

代码
<%@ 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插入功能</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
    
<table border="0" cellpadding="0" cellspacing="0" >
            
<tr>
                
<td style="width: 800px" >
                    已经发布的招代理商:
</td>
            
</tr>
            
<tr>
                
<td style="width: 800px">
                    
<asp:GridView ID="gvAgent" runat="server" AutoGenerateColumns="False" Width="800px" Font-Size="12px" AllowPaging="true" PageSize="5"
                        ShowFooter
="false" DataKeyNames="id" OnRowDeleting="gvAgent_RowDeleting" OnRowEditing="gvAgent_RowEditing"
                        OnRowUpdating
="gvAgent_RowUpdating" OnRowCancelingEdit="gvAgent_RowCancelingEdit" OnRowDataBound="gvAgent_RowDataBound" OnPageIndexChanging="gvAgent_PageIndexChanging">
                        
<Columns>
                        
                        
<asp:TemplateField HeaderText="编号" ItemStyle-Width="50" ControlStyle-Width="50">
                                
                                
<%--自动编号 --%>
                                
<EditItemTemplate>
                                    
<%#Container.DataItemIndex+1%>

                                
</EditItemTemplate>
                                
<ItemTemplate>
                                    
<%#Container.DataItemIndex+1%>

                                
</ItemTemplate>
                                 
<FooterTemplate>
                                    
<%#Container.DataItemIndex+1%>
                                
</FooterTemplate>
                            
</asp:TemplateField>
                        
                        
                          
                            
<asp:TemplateField HeaderText="公司名称" ItemStyle-Width="180">
                                
<EditItemTemplate>
                                    
<asp:TextBox ID="txtEditCompanyName" runat="server" Text='<%# Eval("companyName") %>'></asp:TextBox>
                                
</EditItemTemplate>
                                
<ItemTemplate>
                                    
<asp:Label ID="Label1" runat="server" Text='<%# CommonHandler.SubString(Eval("companyName").ToString(),10) %>'></asp:Label>
                                
</ItemTemplate>
                                
<FooterTemplate>
                                    
<asp:TextBox ID="txtInsertCompanyName" runat="server"></asp:TextBox>
                                
</FooterTemplate>
                            
</asp:TemplateField>
                            
<asp:TemplateField HeaderText="链接URL" ItemStyle-Width="260">
                                
<EditItemTemplate>
                                    
<asp:TextBox ID="txtEditUrl" runat="server" Text='<%# Eval("linkUrl") %>'></asp:TextBox>
                                
</EditItemTemplate>
                                
<ItemTemplate>
                                    
<asp:Label ID="Label2" runat="server" Text='<%# Eval("linkUrl") %>'></asp:Label>
                                
</ItemTemplate>
                                
<FooterTemplate>
                                    
<asp:TextBox ID="txtInsertUrl" runat="server"></asp:TextBox>
                                
</FooterTemplate>
                            
</asp:TemplateField>
                            
<asp:TemplateField HeaderText="添加日期" ItemStyle-Width="150" ControlStyle-Width="150">
                                
<EditItemTemplate>
                                    
<asp:Label ID="Label1" runat="server" Text='<%# Eval("addedDate") %>'></asp:Label>
                                
</EditItemTemplate>
                                
<ItemTemplate>
                                    
<asp:Label ID="Label3" runat="server" Text='<%# Eval("addedDate") %>'></asp:Label>
                                
</ItemTemplate>
                                
<FooterTemplate>
                                
<asp:DropDownList ID="ddlInsertHour" runat="server">
                                    
<asp:ListItem>0</asp:ListItem>
                                    
<asp:ListItem>1</asp:ListItem>
                                    
<asp:ListItem>2</asp:ListItem>
                                    
<asp:ListItem>3</asp:ListItem>
                                    
<asp:ListItem>4</asp:ListItem>
                                    
<asp:ListItem>5</asp:ListItem>
                                    
<asp:ListItem>6</asp:ListItem>
                                    
<asp:ListItem>7</asp:ListItem>
                                    
<asp:ListItem Selected="True">8</asp:ListItem>
                                    
<asp:ListItem>9</asp:ListItem>
                                    
<asp:ListItem>10</asp:ListItem>
                                    
<asp:ListItem>11</asp:ListItem>
                                    
<asp:ListItem>12</asp:ListItem>
                                    
<asp:ListItem>13</asp:ListItem>
                                    
<asp:ListItem>14</asp:ListItem>
                                    
<asp:ListItem>15</asp:ListItem>
                                    
<asp:ListItem>16</asp:ListItem>
                                    
<asp:ListItem>17</asp:ListItem>
                                    
<asp:ListItem>18</asp:ListItem>
                                    
<asp:ListItem>19</asp:ListItem>
                                    
<asp:ListItem>20</asp:ListItem>
                                    
<asp:ListItem>21</asp:ListItem>
                                    
<asp:ListItem>22</asp:ListItem>
                                    
<asp:ListItem>23</asp:ListItem>
                                    
                                
</asp:DropDownList>
                                 
<asp:DropDownList ID="ddlInsertMinute" runat="server">
                                    
<asp:ListItem>00</asp:ListItem>
                                    
<asp:ListItem>5</asp:ListItem>
                                    
<asp:ListItem>10</asp:ListItem>
                                    
<asp:ListItem>15</asp:ListItem>
                                    
<asp:ListItem>20</asp:ListItem>
                                    
<asp:ListItem>25</asp:ListItem>
                                    
<asp:ListItem>30</asp:ListItem>
                                    
<asp:ListItem>35</asp:ListItem>
                                    
<asp:ListItem>40</asp:ListItem>
                                    
<asp:ListItem>45</asp:ListItem>
                                    
<asp:ListItem>50</asp:ListItem>
                                    
<asp:ListItem>55</asp:ListItem>
                                    
<asp:ListItem>60</asp:ListItem>
                                    
                                
</asp:DropDownList>
                                    
                                
</FooterTemplate>
                            
</asp:TemplateField>
                            
<asp:TemplateField HeaderText="顺序">
                                
<EditItemTemplate>
                                    
<asp:TextBox ID="txtEditOrders" runat="server" Text='<%# Eval("orders") %>'></asp:TextBox>
                                
</EditItemTemplate>
                                
<ItemTemplate>
                                    
<asp:Label ID="Label4" runat="server" Text='<%# Eval("orders") %>'></asp:Label>
                                
</ItemTemplate>
                                
<FooterTemplate>
                                    
<asp:TextBox ID="txtInsertOrders" Width="30" runat="server"></asp:TextBox>
                                
</FooterTemplate>
                            
</asp:TemplateField>
                            
<asp:CommandField HeaderText="操作" ItemStyle-Width="100" ShowDeleteButton="True" ShowEditButton="True" />
                        
</Columns>
                        
<RowStyle BackColor="#EFF3FB" Height="28" />
                        
<EditRowStyle BackColor="#2461BF" Height="28" />
                        
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" Height="28" />
                        
<AlternatingRowStyle BackColor="White" />
                    
</asp:GridView>
                
</td>
            
</tr>
            
<tr>
                
<td>
                    
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="添 加" />
                    
<asp:Button ID="btnOk" runat="server" OnClick="btnOk_Click" Text="确 定" />
                    
<asp:Button ID="btnCancel" runat="server" OnClick="btnCancel_Click" Text="取 消" />
                
</td>
            
</tr>
        
</table>
    
</div>
    
</form>
</body>
</html>

 

 

代码
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;





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



    
/// <summary>
    
/// 查询所有的数据
    
/// </summary>
    private void BindData()
    {
        Company company 
= new Company();
        DataSet ds 
= null;
        ds 
= company.GetAgent();

        
this.gvAgent.DataSource = ds;
        
this.gvAgent.DataBind();

    }


    
/// <summary>
    
/// 点击编辑时激发的事件
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>
    protected void gvAgent_RowEditing(object sender, GridViewEditEventArgs e)
    {
        
// 设置当前编辑的索引  e.NewEditIndex 可以获得当前编辑的行
        this.gvAgent.EditIndex = e.NewEditIndex;

        
//记得要重新调用一下绑定数据的方法哦
        BindData();
    }

    
/// <summary>
    
/// 点击更新时激发的事件
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>
    protected void gvAgent_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        
//获得编号 这个编号要在GridView中设置一下属性 DataKeyNames 这里设置的是数据库的主键ID
        
//e.RowIndex 这个通过 事件源 e 来获得RowIndex 代表 行号
        string agentId = this.gvAgent.DataKeys[e.RowIndex].Value.ToString();

        
//  公司名称
        
//  这里是取得编辑时的值
        
//  通过 Rows[e.RowIndex] 当时事件的行 
        
//  Cells[1]代表这一行的第几个单元格  是从 索引是从 0开始的  当前单元格  是第二列的, 所以索引是1 
        
//  Controls[1] 代表这个单元格中的控件 ,索引也是从 0 开始的 插入的文本框 是第二个,所以索引是1
        
//  我们取出来的控件的类型都是Control类型 的,所以,我们要根据我们定义的控件类型去转换,这里是TextBox类型 (注意 括号的加法)

        
//如果是其它类型,就转换成其它的类型就可以了如DropDownList
        string companyName = ((TextBox)(this.gvAgent.Rows[e.RowIndex].Cells[1].Controls[1])).Text.Trim();

        
//同上
        string url = ((TextBox)(this.gvAgent.Rows[e.RowIndex].Cells[2].Controls[1])).Text.Trim();

        
//同上
        string orders = ((TextBox)(this.gvAgent.Rows[e.RowIndex].Cells[4].Controls[1])).Text.Trim();
        
//实例化对象
        Company company = new Company();

        
//调用修改的方法
        int rows = company.ModifyAgentById(int.Parse(agentId), url, companyName, orders);

        
if (rows > 0)
        {
            Page.ClientScript.RegisterStartupScript(
this.GetType(), "PopupScript""alert('修改成功!')"true);
        }
        
else
        {
            Page.ClientScript.RegisterStartupScript(
this.GetType(), "PopupScript""alert('修改失败!')"true);
        }

        
//修改完全后,把EditIndex设置为-1  ,非编辑状态
        this.gvAgent.EditIndex = -1;

        
//记得要重新调用一下绑定数据的方法哦
        BindData();
    }

    
/// <summary>
    
/// 取消编辑
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>
    protected void gvAgent_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        
//也就是设置GridView的EditIndex属性=-1
        this.gvAgent.EditIndex = -1;
        
//记得要重新调用一下绑定数据的方法哦
        BindData();
    }


    
/// <summary>
    
/// 删除
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>
    protected void gvAgent_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        
//管理客户端脚本的类
        ClientScriptManager cs = Page.ClientScript;
        Type cstype 
= this.GetType();



        
int agentId = int.Parse(gvAgent.DataKeys[e.RowIndex].Value.ToString());

        Company company 
= new Company();

        
if (company.DelAgentById(agentId) > 0)
        {
            BindData();
            cs.RegisterStartupScript(cstype, 
"PopupScript""alert('删除成功!')"true);
        }
        
else
        {
            cs.RegisterStartupScript(cstype, 
"PopupScript""alert('删除失败!')"true);
        }
    }

    
/// <summary>
    
/// 添加热钮的事件 
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>
    protected void btnAdd_Click(object sender, EventArgs e)
    {
       
        
        
//让脚部添加的文本框显示出来
        this.gvAgent.ShowFooter = true;
        
//记得要重新调用一下绑定数据的方法哦
        BindData();
    }

    
/// <summary>
    
/// 取消按钮事件
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>
    protected void btnCancel_Click(object sender, EventArgs e)
    {
      
        
//让脚部 添加的文本框不显示
        this.gvAgent.ShowFooter = false;

        
//记得要重新调用一下绑定数据的方法哦
        BindData();
    }

    
/// <summary>
    
/// 添加的操作
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        

        
//公司名称
        string companyName = ((TextBox)this.gvAgent.FooterRow.FindControl("txtInsertCompanyName")).Text.Trim();
        
//网址
        string url = ((TextBox)this.gvAgent.FooterRow.FindControl("txtInsertUrl")).Text.Trim();
        
//取小时
        string hour = ((DropDownList)this.gvAgent.FooterRow.FindControl("ddlInsertHour")).SelectedValue;
        
//取 分钟
        string minute = ((DropDownList)this.gvAgent.FooterRow.FindControl("ddlInsertMinute")).SelectedValue;

        
//顺序
        string orders = ((TextBox)this.gvAgent.FooterRow.FindControl("txtInsertOrders")).Text.Trim();

        
bool flag =CommonHandler.IsNumberic(orders);
        
if (!flag)
        {
             Page.ClientScript.RegisterStartupScript(
this.GetType(), "PopupScript""alert('必须为数字')"true);
        }


        
//得到今天的日期  " 年月日 "  的格式
        string t = DateTime.Now.ToString("yyyy-MM-dd");
        
//把日期和时间连接起来 注意格式 2010-01-20 8:00 这个是字符串格式的
        string time = t + " " + hour + ":" + minute;
        
//把字符串形的日期转换成DateTime格式的
        DateTime insertTime = DateTime.Parse(time);

        
//实例化Company类
        Company company = new Company();

        
//调用方法返回的值
        int rows = 0;

        
//try catch 捕获异常
        try
        {
            
//调用方法,返回值大于 0 说明添加成功,等于=说明添加失败
            rows = company.AddAgent(url, companyName, int.Parse(orders));
        }
        
catch (Exception)
        {
        
//如果有异常,就转到这里,然后提示一下,如果出现了异常,肯定添加也是失败的,所以rows肯定也是0了,所以,赋值一下
            Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript""alert('添加出现异常')"true);
            rows 
= 0;
        }

        
//如果大于0说明添加成功,否则添加失败
        if (rows>0)
        {
            Page.ClientScript.RegisterStartupScript(
this.GetType(), "PopupScript""alert('添加成功')"true);
        }
        
else
        {
            Page.ClientScript.RegisterStartupScript(
this.GetType(), "PopupScript""alert('添加失败')"true);
        }

        
this.gvAgent.ShowFooter = false;
        BindData();
    }

    
protected void gvAgent_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        
//鼠标 移上去的时候变色
        CommonHandler.ChangeGridViewColor(sender,e,"#bbb");
    }
    
protected void gvAgent_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        
this.gvAgent.PageIndex= e.NewPageIndex;
        BindData();
    }
}