海海日记-冯海滨博客

您现在的位置是:首页 > C# > 正文

C#

GridView中行的编辑与删除

happyfhb2012-09-20C#1421

效果:

 

GridView设置注意:

点控件右上角的小三角>编辑列

需要多少字段就添加多少个BoundField,并在每个中设好属性,DataField为数据库字段的名称,HeaderText为控件中相应列显示的字段。

编辑与取消的列在CommandField中,添加。

取消左下角“自动生成字段”的勾

 

 

 

 

 

 

 

 

代码:

重点难点已经注释。

 

(引用)

using System.Data.SqlClient;

 

public partial class _Default : System.Web.UI.Page

{

    SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=MySql;Integrated Security=True");

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)//判定是否第一次加载,必须的,否则编辑中的数据更新不了

        {

            bind();

        }

    }

    //绑定数据

    public void bind()

    {

        DataSet ds = new DataSet();

        SqlDataAdapter da = new SqlDataAdapter("select * from student", conn);

        da.Fill(ds);

        GridView1.DataSource = ds;

        GridView1.DataKeyNames = new string[] { "id" };//设“id”为标识

        GridView1.DataBind();

    }

    //删除当前行

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

        string commString = String.Format("delete from student where id='{0}'",

            GridView1.DataKeys[e.RowIndex ].Value .ToString ());//取出当前行的标识

        SqlCommand comm = new SqlCommand(commString,conn);

        conn.Open();

        comm.ExecuteNonQuery();

        conn.Close();

        bind();

    }

    //编辑当前行

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

    {

        GridView1.EditIndex = e.NewEditIndex;//对所在行进行编辑

        bind();

    }

    //更新编辑

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

        string commString = String.Format("update student set name='{0}',sex='{1}',age='{2}' where id='{3}'",

            ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim(),//当前行的,第1列(从0开始),第0个控件

            ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim(),

            ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim(),

            GridView1.DataKeys[e.RowIndex].Value.ToString());

        SqlCommand comm = new SqlCommand(commString, conn);

        conn.Open();

        comm.ExecuteNonQuery();

        conn.Close();

        GridView1.EditIndex = -1;//取消编辑

        bind();

    }

    //取消编辑

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        GridView1.EditIndex = -1;

        bind();

    }  

}

 

注:“Page_Load()”中绑定的方法“bind()”一定要有if (!IsPostBack){}包含,否则更新数据将不可用。

 

平淡中储蓄成长

发表评论

评论列表

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~