GridView 批量修改
<div>
<asp:GridView ID="GridView1" runat="server" Font-Size="12px" CellPadding="3" AutoGenerateColumns="False"
DataKeyNames="employeeid" >
<HeaderStyle BackColor="#EDEDED" />
<Columns>
<asp:TemplateField HeaderText="编号">
<ItemTemplate>
<asp:TextBox ID="employeeid" runat="server" Text='<%#Eval("employeeid") %>' ></asp:TextBox>
</ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="姓">
<ItemTemplate>
<asp:TextBox ID="lastname" runat="server" Text='<%#Eval("lastname") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="名">
<ItemTemplate>
<asp:TextBox ID="firstname" runat="server" Text='<%#Eval("firstname") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="保存所有修改" OnClick="Button1_Click" />
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class txt_uoALLdate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//绑定GRIDVIEW打开页面显示数据
GridViewbind();
}
}
private void GridViewbind()
{
//连接字符串WEB.CONFIG里面的
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from employees";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "employee");
this.GridView1.DataSource = ds.Tables["employee"];
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in GridView1.Rows)
{
string con = System.Configuration.ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRING"].ConnectionString;
SqlConnection conn = new SqlConnection(con);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update employees set lastname=@lastname,firstname=@firstname where employeeid=@employeeid";
cmd.Parameters.Add("@lastname", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("@firstname", SqlDbType.NVarChar, 10);
cmd.Parameters.Add("@employeeid", SqlDbType.Int);
cmd.Parameters["@lastname"].Value = ((TextBox)gvr.FindControl("lastname")).Text;
cmd.Parameters["@firstname"].Value = ((TextBox)gvr.FindControl("firstname")).Text;
cmd.Parameters["@employeeid"].Value = ((TextBox)gvr.FindControl("employeeid")).Text;
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
finally
{
if (conn != null)
conn.Dispose();
}
}
}
}