前台代码:
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Width="281px" CellPadding="4" ForeColor="#333333" GridLines="None">
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="id">
<ItemTemplate>
<%--修改时候的where 条件,必须--%>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="标识">
<ItemTemplate>
<%--修改的数据就是在这了 ^-^ --%>
<asp:TextBox ID="TextBox1" runat="server" Text =' <%# Bind("name") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<asp:Button ID="Button1" runat="server" οnclick="Button1_Click" Text="Button" />
</form>
</body>
后台代码:
private SqlConnection con;
private string conString = ConfigurationManager.ConnectionStrings["CONNECTIONSTRING"].ToString();
private string strSql;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//初始化绑定,写程序时候,最好你把它写到一个方法中。这里为了省事,比较懒
SqlDataAdapter da;
try
{
//创建dataset实例
ds = new DataSet();
//创建连接
con = new SqlConnection(conString);
//打开连接
con.Open();
//sql 文
strSql = "select * from STUDENT_UPDATE ";
//strSql = "select t.STU_ID,t.STU_NAME,t.STU_AGE,t.STU_XUELI,(case t.STU_SEX when '1' then '男' else '女' end) as sex,";
//strSql += " t.STU_SCHOOL,x.STU_TEXT as STU_TEXT,t.STU_SEX";
//strSql += " from STUDENT_TEST t left outer join STUDENT_XUELI x on t.STU_XUELI = x.STU_ID ";
//创建sqldataadaper
da = new SqlDataAdapter(strSql, con);
//填充dataset
da.Fill(ds, "aa");
//gridview绑定
GridView1.DataSource = ds.Tables["aa"];
GridView1.DataBind();
//关闭连接
con.Close();
}
catch (SqlException ex)
{
//此句没有用 ,不过可以用来打印异常,这里没有打印
string aa = ex.ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter da;
foreach (GridViewRow gvr in GridView1.Rows)
{
//string con = System.Configuration.ConfigurationManager.AppSettings["ConnectionString1"].ToString();
SqlConnection conn = new SqlConnection(conString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update STUDENT_UPDATE set name = @name where id=@id";
cmd.Parameters.Add("@name",SqlDbType.VarChar,20);
cmd.Parameters.Add("@id",SqlDbType.Int);
cmd.Parameters["@name"].Value = ((TextBox)gvr.FindControl("TextBox1")).Text;
cmd.Parameters["@id"].Value = ((Label)gvr.FindControl("Label1")).Text;
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
finally
{
if (conn != null)
conn.Dispose();
}
}
}
}