保存到数据库中去。那么在Gridview中应该如何实现呢?在Gridview中,有两种实现的方法,下面分别进行介绍:
先来看下第一种方法,本方法是使用sqldatasource来更新所有记录,但这个方法比较慢,因为每更新一条记录都要建立数据连接并执行updatecommand,会影响性能。其主要代码如下:
<script runat="server">
void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < Gridview1.Rows.Count; i++)
{
GridviewRow row = Gridview1.Rows[i];
SqlDataSource1.UpdateParameters[0].DefaultValue = ((TextBox)row.Cells[0].FindControl("TextBox2")).Text;
SqlDataSource1.UpdateParameters.DefaultValue = ((TextBox)row.Cells.FindControl("TextBox3")).Text;
SqlDataSource1.UpdateParameters.DefaultValue = Gridview1.DataKeys[i].Value.ToString();
SqlDataSource1.Update();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Gridview ID="Gridview1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField SortExpression="CustomerID" HeaderText="CustomerID">
<ItemTemplate>
<asp:TextBox Runat="server" Text=’<%# Bind("CustomerID") %>’ ID="TextBox1"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="CompanyName" HeaderText="CompanyName">
<ItemTemplate>
<asp:TextBox Runat="server" Text=’<%# Bind("CompanyName") %>’ ID="TextBox2"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:Templat