.NET中GridView的删除、修改、分页等功能全面图解

下图所示:GridView控件一般要处理6类事件。

GridView1_PageIndexChanging:分页
GridView1_RowDeleting:删除
GridView1_RowEditing:编辑
GridView1_RowUpdating:修改
GridView1_RowCancelingEdit:取消编辑
GridView1_RowDataBound:数据绑定的一些相关处理
设置GridView的主键:

将主键设置为只读:

代码页面我们首先要绑定数据源:
/// <summary>
/// 绑定数据
/// </summary>
private void bindData()
{
this.GridView1.DataSource =数据源;
this.GridView1.DataBind();
}页面加载时进行绑定:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
bindData();
}
}分页处理:
/// <summary>
/// 分页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.GridView1.PageIndex = e.NewPageIndex;
this.bindData();
}
分页需要的设置(allowpaging设置为true,pagesize设置为每页的数据数目:

删除数据处理:
/// <summary>
/// 删除
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(this.GridView1.Rows[e.RowIndex].Cells[0].Text);//获取当前gridview的主键值
mypotpublcxmclass.Delete(id);

this.bindData();
}
触发编辑事件:
/// <summary>
/// 编辑
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
this.GridView1.EditIndex = e.NewEditIndex;
this.bindData();
}修改数据处理:
/// <summary>
/// 修改
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string newvalue=((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;//获取新值
int id = Convert.ToInt32(this.GridView1.Rows[e.RowIndex].Cells[0].Text);//获取当前gridview的主键值
//我的修改代码
Model.alldeadmin.t_public_xmclass mymodeltpx = new Model.alldeadmin.t_public_xmclass();
mymodeltpx.id =id;
mymodeltpx.classname = newvalue;
mytpxm.Update(mymodeltpx);
//修改代码操作完毕
this.GridView1.EditIndex = -1;
this.bindData();

}
单击取消编辑的按钮处理:
/// <summary>
/// 取消编辑
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.GridView1.EditIndex = -1;
this.bindData();
}单击删除后给客户提示是否删除的代码:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//如果是绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[this.GridView1.Columns.Count - 1].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除编号为:"" + e.Row.Cells[0].Text + ""的数据吗?')");
}
}
}

OK,GridView的基本操作介绍完毕。

文章来源(WEB开发技术知识库):http://www.cn-web.com/cnweb/14/471/article/

你可能感兴趣的:(.NET中GridView的删除、修改、分页等功能全面图解)