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 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);
您可能感兴趣的文章: