GridView常用增删改的示例(以后方便备用)
代码
//GridView的绑定方法一定要在!ISPOSTBACK中private void bind()
{
GridView1.DataKeyNames = new string[] { "id" };//DataKeyNames为数组id 下面好调用 重要GridView1.DataSource = new xh.shop.DAL.news_category().GetList("");
GridView1.DataBind();
}//绑定函数
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{ //进入编辑栏状态
GridView1.EditIndex = e.NewEditIndex;
bind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{//更新方法
string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
//取出ID值
string name = ((System.Web.UI.WebControls.TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).FindControl("TextBox1")).Text.ToString().Trim();//取得文本框中输入的值注意.FindControl("TextBox1")的使用一般情况下不用 除非出错
//下面调用更新方法 我使用的是更新实体库
if (name.Length == 0)
{
Response.Write("<script language='JavaScript'>alert('请不要为空')</script>");
return;
}
//判断是否为空
if (!new xh.shop.DAL.news_category().Exists(name))
{
Response.Write("<script language='JavaScript'>alert('类别重复')</script>");
((System.Web.UI.WebControls.TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).FindControl("TextBox1")).Text = "";
return;
}
//判断是否有重复类容 判断条件是自己定义的方法
xh.shop.Model.news_category model =new xh.shop.Model.news_category();//自定义的实体
model.id=Convert.ToInt32( id);
model.name=name;
new xh.shop.DAL.news_category().Update(model);//更新自定义的实体
//返回状态绑定数据
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//取消状态
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{//删除状态
string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
//取出ID值
Response.Write("<script language='JavaScript'>return confirm('是否删除') </script>");
new xh.shop.DAL.news_category().Delete(Convert.ToInt32(id));
Response.Write("<script language='JavaScript'>alert('删除成功')</script>");
bind();
}