ASP.NET2.0中用Gridview控件操作数据
2、一次性更新所有的Gridview记录
我们经常会遇到这样的情况,在Gridview中列出的所有记录中,有时要同时修改多条记录,并且将其保存到数据库中去。那么在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[1].DefaultValue =
((TextBox)row.Cells[1].FindControl("TextBox3")).Text; SqlDataSource1.UpdateParameters[2].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:TemplateField SortExpression="ContactName" HeaderText="ContactTitle"> <ItemTemplate> <asp:TextBox Runat="server" Text=’<%# Bind("ContactTitle") %>
’ ID="TextBox3"></asp:TextBox> </ItemTemplate> </asp:TemplateField> </Columns> </asp:Gridview> <asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT [CustomerID], [CompanyName],
[ContactName], [ContactTitle] FROM [Customers]" UpdateCommand="UPDATE [Customers] SET [CompanyName] =
@CompanyName, [ContactTitle] = @ContactTitle WHERE [CustomerID] = @CustomerID" ConnectionString="server=localhost;uid=sa;password=xxxx;database=northwind"> <UpdateParameters> <asp:Parameter Type="String" Name="CompanyName"></asp:Parameter> <asp:Parameter Type="String" Name="ContactTitle"></asp:Parameter> <asp:Parameter Type="String" Name="CustomerID"></asp:Parameter> </UpdateParameters> </asp:SqlDataSource> <asp:Button ID="Button1" Runat="server" Text="Button" OnClick="Button1_Click" /> </div> </form> </body> </html>
在上面的代码中,我们必须首先指定updateparameters参数集合,也就是指出要更新的是哪些字段,它们的类型是什么。之后并指出sqldatasource的updatecommand语句。而在更新按钮button1的CLICK事件中,将以遍历的形式,使用for循环,对Gridview中的每一行进行检查,将每个更新了的文本框的内容放到sqldatasouce的updateparameters参数中去,最后调用sqldatasource的update方法,完成更新。
方法2使用的是首先遍历Gridview中的每一行,并且使用SQL语句,将要更新的内容连接起来,然后最后才使用command.ExecuteNonQuery()进行更新,效率高了,主要代码如下:
protected void Page_Load(object sender, EventArgs e)
...{
![]()
if (!Page.IsPostBack)
...{
SqlConnection con = new SqlConnection(ConfigurationManager
.ConnectionStrings["AppConnectionString1"].ConnectionString);SqlCommand command = new SqlCommand("SELECT [CustomerID],
[CompanyName], [ContactName], [ContactTitle] FROM [Customers]", con);con.Open();
Gridview1.DataSource = command.ExecuteReader();
Gridview1.DataBind();
con.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
...{
StringBuilder query = new StringBuilder();
for (int i = 0; i < Gridview1.Rows.Count; i++)
...{
GridviewRow row = Gridview1.Rows[i];
string value1 = ((TextBox)row.Cells[0].FindControl("TextBox2"))
.Text.Replace("’", "’’");string value2 = ((TextBox)row.Cells[1].FindControl("TextBox3"))
.Text.Replace("’", "’’");string value3 = Gridview1.DataKeys[i].Value.ToString();
query.Append("UPDATE [Customers] SET [CompanyName] = ’")
.Append(value1).Append("’ , [ContactTitle] = ’").Append(value2).Append("’ WHERE [CustomerID] = ’").Append(value3).Append("’;\n");
}
![]()
SqlConnection con = new SqlConnection(ConfigurationManager
.ConnectionStrings["AppConnectionString1"].ConnectionString);SqlCommand command = new SqlCommand(query.ToString(), con);
con.Open();
command.ExecuteNonQuery();
con.Close();
}
}
其中要特别注意一点的是,在VS.NET 2005 beta 2开始,如果你在Web.config中使用了数据库连接字符串的配置,那么应该按如下的方法去写:
<connectionStrings> <add name="NorthwindConnectionString" connectionString=
"Data Source=LIAO;Initial Catalog=Northwind;User ID=sa;
Password=xxxx" providerName="System.Data.SqlClient"/> </connectionStrings>
然后在程序中如下进行读取:
SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["AppConnectionString1"].ConnectionString);
0
相关文章
