![](/images/blog_csdn_net/web718/datagrid3.jpg)
<%@ Page language="c#" Codebehind="DataGridEdit.aspx.cs" AutoEventWireup="false" Inherits="News.DataGridEdit" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>DataGridEdit</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="DataGridEdit" method="post" runat="server">
<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="100%" border="0">
<TR>
<TD>
<asp:DataGrid id="DataGrid1" DataKeyField="id" runat="server" Width="50%" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4" AutoGenerateColumns="False">
<SelectedItemStyle Font-Bold="True" ForeColor="#CCFF99" BackColor="#009999"></SelectedItemStyle>
<ItemStyle ForeColor="#003399" BackColor="White"></ItemStyle>
<HeaderStyle Font-Bold="True" ForeColor="#CCCCFF" BackColor="#003399"></HeaderStyle>
<FooterStyle ForeColor="#003399" BackColor="#99CCCC"></FooterStyle>
<Columns>
<asp:TemplateColumn HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.id") %>' ID="Label1" NAME="Label1">
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="姓名">
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.username") %>' ID="Label2" NAME="Label2">
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Email">
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.email") %>' ID="Label3" NAME="Label3">
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtEmail" Text='<%# DataBinder.Eval(Container, "DataItem.email") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="<img src=images/save.gif border=0 alt='保存'/>" CancelText="<img src=images/cancel.gif border=0 alt='取消'/>" EditText="<img src=images/edit.gif border=0 alt='编辑'/>"></asp:EditCommandColumn>
</Columns>
</asp:DataGrid>
</TD>
</TR>
<TR>
<TD></TD>
</TR>
<TR>
<TD></TD>
</TR>
</TABLE>
</form>
</body>
</HTML>
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
namespace News
{
/// <summary>
/// DataGridEdit 的摘要说明。
/// </summary>
public class DataGridEdit : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid DataGrid1;
string ConnectionStr=ConfigurationSettings.AppSettings["connStr"];//连接数据库
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
BindGrid();
}
}
//绑定数据库
private void BindGrid()
{
//定义数据连接对象,其中数据库连接字符串是在Web.Config文件中定义的
SqlConnection SconnStr=new SqlConnection(ConnectionStr);
//创建数据适配器对象
SqlDataAdapter sda=new SqlDataAdapter("select * from user_info",SconnStr);
//创建DataSet对象
DataSet ds=new DataSet();
try
{
//填充数据集
sda.Fill(ds,"user_info");
//进行数据绑定
DataGrid1.DataSource=ds.Tables["user_info"];
DataGrid1.DataBind();
}
catch(Exception error)
{
Response.Write(error.ToString());
}
finally{}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_CancelCommand);
this.DataGrid1.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_EditCommand);
this.DataGrid1.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_UpdateCommand);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
//设置DataGrid控件的编辑项的索引为选择的当前项
DataGrid1.EditItemIndex = e.Item.ItemIndex;
//数据绑定
BindGrid();
}
private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
//取得编辑行的关键字段的值
int empID=(int)DataGrid1.DataKeys[e.Item.ItemIndex];
//取得文本框中输入的内容
TextBox newEmail = (TextBox)e.Item.FindControl("txtEmail");
//定义SQL语句
string sqlCom = "update user_info set email='" + newEmail.Text + "' where id="+empID.ToString();
//定义数据连接对象,其中数据库连接字符串是在Web.Config文件中定义的
SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["connStr"].ToString());
//定义命令对象
SqlCommand cmd = new SqlCommand(sqlCom,conn);
//打开数据连接
conn.Open();
try
{
//执行SQL命令
cmd.ExecuteNonQuery();
//取消编辑
DataGrid1.EditItemIndex = -1;
BindGrid();
}
catch(Exception err)
{
//输出异常信息
Response.Write(err.ToString());
}
finally
{
//关闭连接对象
conn.Close();
}
}
private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
//设置DataGrid控件的编辑项的索引为-1,既取消编辑
DataGrid1.EditItemIndex = -1;
//数据绑定
BindGrid();
}
}
}