Default.aspx
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>
Default.aspx.cs
View Code
View Code using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; //引入命名空间 using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //创建数据库连接对象 SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["strCon"]); //创建数据适配器 SqlDataAdapter da = new SqlDataAdapter("select ID,Name,Price from bccd", con); DataSet ds = new DataSet();//创建数据集 da.Fill(ds, "Bccd");//填充数据集 //调用自定义方法ShowDsTable显示未更新前的数据信息 ShowDsTable(ds.Tables[0]); //清空内存表中数据 ds.Tables.Clear(); //给SqlDataAdapter的UpdateCommand属性指定执行更新操作的SQL语句 da.UpdateCommand = new SqlCommand("update bccd set Name = @Name where ID=@id", con); //添加参数并赋值 da.UpdateCommand.Parameters.Add("@Name", SqlDbType.NVarChar, 800, "Name"); SqlParameter prams_ID = da.UpdateCommand.Parameters.Add("@id", SqlDbType.Int); prams_ID.SourceColumn = "ID"; prams_ID.SourceVersion = DataRowVersion.Original; //填充数据集 da.Fill(ds, "Bccd"); //应用一个for循环更改数据集ds的MRBccd表中brccdName列的值 for (int i = 0; i <= ds.Tables["Bccd"].Rows.Count-1; i++) { ds.Tables["Bccd"].Rows[i]["Name"] += DateTime.Today.ToShortDateString(); } //调用Update方法提交更新后的数据集ds,并同步更新数据库数据 da.Update(ds, "Bccd"); //调用自定义方法ShowDsTable显示更新后的数据 ShowDsTable(ds.Tables[0]); } public void ShowDsTable(DataTable dataTable) { foreach (DataRow row in dataTable.Rows) { //输出表格 Response.Write("<table border=1 align='center' "); Response.Write("<tr><th>编号</th><th>名称</th><th>价格</th></tr>"); Response.Write("<tr>"); for (int i = 0; i < dataTable.Columns.Count; i++) { //按照顺序以列名指定要读取的项 Response.Write("<td align='center'>" + row[i] + "</td>"); } Response.Write("</tr>"); Response.Write("</table>"); } } }