使用单击和双击更新DataGrid中的数据的例子

可能大家在使用DataGrid编辑数据的时候会觉得要点击最后的编辑列的按钮来修改数据不是很方便,在今天的例子中给出一种比较方便的操作方法:要修改数据点击这一行-》鼠标放在哪个文本框就会选中哪个文本框的内容,直接可以进行修改-》修改完毕以后双击这一行(也可以直接双击文本框)进行保存。这次使用sqlserver数据库中的northwind数据库中的Employees表作为例子。

前台:

<%@ Page language="c#" Codebehind="WebForm87.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm87" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    <HEAD>
        <title>WebForm87</title>
        <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
        <meta content="C#" name="CODE_LANGUAGE">
        <meta content="JavaScript" name="vs_defaultClientScript">
        <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
        <LINK href="css.css" type="text/css" rel="stylesheet">
    </HEAD>
    <body>
        <form id="Form1" method="post" runat="server">
            <asp:datagrid id="DataGrid1" runat="server" AutoGenerateColumns="False" CellSpacing="1" BorderWidth="0px"
                CellPadding="5" CssClass="border" DataKeyField="EmployeeID">
                <ItemStyle CssClass="item"></ItemStyle>
                <HeaderStyle CssClass="header"></HeaderStyle>
                <Columns>
                    <asp:BoundColumn DataField="FirstName" HeaderText="FirstName"></asp:BoundColumn>
                    <asp:BoundColumn DataField="LastName" HeaderText="LastName"></asp:BoundColumn>
                    <asp:BoundColumn DataField="Title" HeaderText="Title"></asp:BoundColumn>
                    <asp:BoundColumn DataField="BirthDate" HeaderText="BirthDate" DataFormatString="{0:yyyy-MM-dd}"></asp:BoundColumn>
                    <asp:ButtonColumn ButtonType="LinkButton" CommandName="edit" Text="edit" Visible="False"></asp:ButtonColumn>
                    <asp:ButtonColumn ButtonType="LinkButton" CommandName="update" Text="update" Visible="False"></asp:ButtonColumn>
                </Columns>
            </asp:datagrid>
        </form>
    </body>
</HTML>


后台:


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace csdn
{
    public class WebForm87 : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.DataGrid DataGrid1;
   
        private void Page_Load(object sender, System.EventArgs e)
        {
            if(!IsPostBack)
            {
                SetBind();
            }
        }

        private void SetBind()
        {
            SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["strconn"]);
            SqlDataAdapter da=new SqlDataAdapter("select * from Employees",conn);
            DataSet ds=new DataSet();
            da.Fill(ds,"table1");
            this.DataGrid1.DataSource=ds.Tables["table1"];
            this.DataGrid1.DataBind();           
        }

        #region Web 窗体设计器生成的代码
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }
       
        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {   
            this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
            this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem)
            {
                e.Item.Attributes.Add("onclick","__doPostBack('"+((LinkButton)e.Item.Cells[4].Controls[0]).ClientID.Replace("__","$_")+"','')");
            }
            if(e.Item.ItemType==ListItemType.EditItem)
            {
                e.Item.Attributes.Add("ondblclick","__doPostBack('"+((LinkButton)e.Item.Cells[5].Controls[0]).ClientID.Replace("__","$_")+"','')");
                for(int i=0;i<4;i++)((TextBox)e.Item.Cells[i].Controls[0]).Attributes.Add("onmouseover","this.select()");
            }
        }

        private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            if(e.CommandName=="edit")
            {
                this.DataGrid1.EditItemIndex=e.Item.ItemIndex;
                SetBind();
            }
            if(e.CommandName=="update")
            {
                try
                {
                    SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["strconn"]);
                    SqlCommand comm=new SqlCommand("update Employees set FirstName=@FirstName,LastName=@LastName,Title=@Title,BirthDate=@BirthDate where EmployeeID=@EmployeeID",conn);
                    SqlParameter parm1=new SqlParameter("@FirstName",SqlDbType.NVarChar,20);
                    parm1.Value=((TextBox)e.Item.Cells[0].Controls[0]).Text;
                    SqlParameter parm2=new SqlParameter("@LastName",SqlDbType.NVarChar,10);
                    parm2.Value=((TextBox)e.Item.Cells[1].Controls[0]).Text;
                    SqlParameter parm3=new SqlParameter("@Title",SqlDbType.NVarChar,20);
                    parm3.Value=((TextBox)e.Item.Cells[2].Controls[0]).Text;
                    SqlParameter parm4=new SqlParameter("@BirthDate",SqlDbType.DateTime);
                    parm4.Value=((TextBox)e.Item.Cells[3].Controls[0]).Text;
                    SqlParameter parm5=new SqlParameter("@EmployeeID",SqlDbType.Int);
                    parm5.Value=this.DataGrid1.DataKeys[e.Item.ItemIndex];
                    comm.Parameters.Add(parm1);
                    comm.Parameters.Add(parm2);
                    comm.Parameters.Add(parm3);
                    comm.Parameters.Add(parm4);
                    comm.Parameters.Add(parm5);
                    conn.Open();
                    comm.ExecuteNonQuery();
                    conn.Close();
                }
                catch
                {
                    Response.Write("<script>alert('输入的数据格式有误');</script>");
                }
                finally
                {
                    this.DataGrid1.EditItemIndex=-1;
                    SetBind();
                }
            }
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值