源文件中添加代码:
<Columns>
<asp:BoundField DataField="ID" HeaderText="编号" />
<asp:TemplateField HeaderText="教师姓名">
<ItemTemplate>
<asp:TextBox Runat="server" Text='<%# Bind("name") %>' ID="txtName" Height="22px" Width="90px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="教师性别">
<ItemTemplate>
<asp:TextBox Runat="server" Text='<%# Bind("sex") %>' ID="txtSex" Height="22px" Width="54px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="年龄">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("age") %>' ID="txtAge"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="家庭地址">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("address") %>' ID="txtAddress"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
编写代码:
using System.Data.SqlClient;
using System.Text;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Bind();
}
}
//自定义方法,用于检索数据表中的所有数据,并绑定到GridView控件中
public void Bind()
{
string strCon = @"server=TRIMPS-WZF-PC\SQL2005; database=db_09; uid=sa; pwd= ";
string sqlStr = "select * from tb_user";
SqlConnection conn = new SqlConnection(strCon);
SqlDataAdapter myda = new SqlDataAdapter(sqlStr, conn);
DataSet myds = new DataSet();
conn.Open(); //打开数据库连接
myda.Fill(myds,"tb_user");
GridView1.DataSource = myds;
GridView1.DataBind();
conn.Close(); //关闭数据库连接
}
//修改当前分页中的所有行的数据。
//思路是遍历 GridView 控件中的所有行获取每行中文本框中的内容,然后批量修改数据表中相应的数据
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder query = new StringBuilder(); //创建StringBuilder对象
string strCon = @"server=TRIMPS-WZF-PC\SQL2005; database=db_09; uid=sa; pwd= ";
SqlConnection conn = new SqlConnection(strCon);
for (int i = 0; i < GridView1.Rows.Count; i++) //遍历所有行
{
GridViewRow row = GridView1.Rows[i]; //实例化GridViewRow对象
//获取每行中文本框的值
string value1 = ((TextBox)row.Cells[1].FindControl("txtName")).Text.Replace("'", "''"); //关系到源文件中的代码,要仔细研究
string value2 = ((TextBox)row.Cells[2].FindControl("txtSex")).Text.Replace("'", "''");
string value3 = ((TextBox)row.Cells[3].FindControl("txtAge")).Text.Replace("'", "''");
string value4 = ((TextBox)row.Cells[4].FindControl("txtAddress")).Text.Replace("'", "''");
string value = GridView1.DataKeys[i].Value.ToString(); //获取关键字段的值
//自定义update语句并添加到StringBuilder对象中
query.Append("update [tb_user] set [name]= '")
.Append(value1).Append("',[sex]='")
.Append(value2).Append("',[age]='")
.Append(value3).Append("',[address]='")
.Append(value4).Append("'where [ID]='")
.Append(value).Append("';\n");
}
conn.Open();
SqlCommand comm = new SqlCommand(query.ToString(), conn);
if ((Convert.ToInt32(comm.ExecuteNonQuery() )> 0))
{
Response.Write("<script>alert('一次修改数据成功!')</script>");
}
else
{
Response.Write("<script>alert('一次修改数据失败!')</script>");
}
conn.Close();
Bind();
}
界面图: