在GridView中进行编辑,更新和取消操作

      在开发中用到GridView控件,需要种种操作,在网上看到了很多高手的写法,我在这里也借鉴了CSDN上清清月儿的写法,先写编辑,更新和取消操作的方法。

              <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
            ForeColor="#333333" GridLines="None" AllowSorting="True" OnRowCancelingEdit="GridView1_RowCancelingEdit"
            OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" PageSize="8" OnRowEditing="GridView1_RowEditing">
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="UserID" HeaderText="用户ID" ReadOnly="True" />
                <asp:BoundField DataField="User_Nm" HeaderText="用户姓名" />
                <asp:BoundField DataField="User_Sex" HeaderText="性别" />
                <asp:BoundField DataField="User_Address" HeaderText="家庭住址" />
                <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
                <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
                <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
            </Columns>
            <RowStyle ForeColor="#008066" />
            <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
        </asp:GridView>

逻辑代码如下:

      

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = "Data Source=.\\SQL2005;DataBase=Users;Uid=sa;Pwd=123";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }

    public void bind()
    {
        string sqlstr = "Select * from Users";
        sqlcon = new SqlConnection(strCon);
        sqlcon.Open();
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();

        myda.Fill(myds, "AllUsers");
        GridView1.DataSource = myds;

        //Primary key
        GridView1.DataKeyNames = new string[] { "UserID" };

        //绑定数据
        GridView1.DataBind();
        sqlcon.Close();
    }

    /// <summary>
    /// 对GridView中的数据进行删除操作
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string sqlstr = "DELETE FROM USERS WHERE UserID ='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";

        sqlcon = new SqlConnection(strCon);
        sqlcom = new SqlCommand(sqlstr, sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        sqlcon.Open();
        string sqlstr = "UPDATE Users SET User_Nm='"
            + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "' , User_Sex='"
            + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "' ,User_Address='"
            + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' WHERE UserID='"
            + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
        sqlcom = new SqlCommand(sqlstr, sqlcon);
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();

        GridView1.EditIndex = -1;//不可编辑

        bind();
    }


    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        bind();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
}

原文地址:https://www.cnblogs.com/daiweixm/p/1525349.html