如何更新gridview中的值?

时间:2011-12-19 10:46:31

标签: c# asp.net sql-server-2005 webforms

我在.aspx页面中有一个网格,其中包含三个文本字段,如nameidrole,还有一个编辑按钮,您可以在其中单击此行的值显示在txtname,txtid,txtroll

此值我想更新并插入数据库。

1 个答案:

答案 0 :(得分:4)

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Update")
    {
        string uname = "";
        int index = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = GridView1.Rows[index];
        TextBox txtbox1_val = (TextBox)row.FindControl("TxtChangeActive");
        uname = Server.HtmlDecode(row.Cells[1].Text.ToString());
        string upd_query = "update login set active='" + txtbox1_val.Text + "' where uname='" + uname + "' ";
        SqlConnection con = new SqlConnection(conn);
        con.Open();
        SqlCommand cmd = new SqlCommand(upd_query, con);
        cmd.ExecuteNonQuery();

        string query_login = "select * from Login";
        SqlDataAdapter da_login = new SqlDataAdapter(query_login, con);
        DataSet ds_login = new DataSet();
        da_login.Fill(ds_login);
        GridView1.DataSource = ds_login;
        GridView1.DataBind();
    }
}
 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

}

在设计页面

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" 
    AlternatingRowStyle-BackColor="#006699"  
        AlternatingRowStyle-ForeColor="#FFFFFF" onrowupdating="GridView1_RowUpdating">
    <Columns >

    <asp:BoundField HeaderText="Name" DataField="uname" />
    <asp:BoundField HeaderText="Pass" DataField="upass"/>
    <asp:TemplateField>
    <HeaderTemplate>Active</HeaderTemplate>
    <ItemTemplate >
    <asp:TextBox ID="TxtChangeActive" runat="server" Text='<%#Eval("active")%>'></asp:TextBox>
    </ItemTemplate>
    </asp:TemplateField>
     <asp:ButtonField CommandName="Update" Text="Update" />
    </Columns>
    </asp:GridView>