一聚教程网:一个值得你收藏的教程网站

热门教程

asp.net GridView手写事件,包括取主键、取值、更新、选择、删除

时间:2022-06-25 03:57:39 编辑:袖梨 来源:一聚教程网

刚才在调整网站友情链接管理页面,里面有个简单的GridView。因为更改了架构,所以需要手工给GridView编写编辑、删除等事件。最近也经常碰到有人问我GridView的问题,于是写成经验之书以警后人。

图片是本网站后台的友情链接管理页面:
image
 
 

前两者的代码比较固定,一般都是:

 代码如下 复制代码
protected void gvFriendLink_RowEditing(object sender, GridViewEditEventArgs e)
{
gvFriendLink.EditIndex = e.NewEditIndex;
FetchData();
}

protected void gvFriendLink_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvFriendLink.EditIndex = -1;
FetchData();
}
其中,FetchData()是给GridView绑定数据的方法。EditIndex = -1的意思是退出编辑模式。

2. 在RowUpdating事件中的取值问题

2.1 取不到值

如果你直接访问GridView.Row[i].Cell[j].Text是没用的。因为在编辑模式下,这个Cell里其实是有控件的,在这个例子里是个TextBox。所以我们需要强制类型转换一下:

 代码如下 复制代码
protected void gvFriendLink_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GeekStudio.ORM.Model.FriendLink model = new GeekStudio.ORM.Model.FriendLink()
{
Id = Convert.ToInt32(((TextBox)gvFriendLink.Rows[gvFriendLink.EditIndex].Cells[1].Controls[0]).Text),
Title = ((TextBox)gvFriendLink.Rows[gvFriendLink.EditIndex].Cells[2].Controls[0]).Text,
Url = ((TextBox)gvFriendLink.Rows[gvFriendLink.EditIndex].Cells[3].Controls[0]).Text,
OrderId = Convert.ToInt32(((TextBox)gvFriendLink.Rows[gvFriendLink.EditIndex].Cells[4].Controls[0]).Text)
};

optFriendLink.Update(model);

gvFriendLink.EditIndex = -1;
FetchData();
}
2.2 取不到新值

如果你在GridView编辑的时候,明明填写了新值,更新之后却不变,比如单元格里原先是abc,你编辑的时候写了abcd,走到更新事件中,获取的值还是abc。这时候你要检查,你是不是忘记判断页面PostBack了?

解决办法:把数据绑定方法写在if(!Page.IsPostBack)里面

 代码如下 复制代码
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FetchData();
}
}

protected void FetchData()
{
gvFriendLink.DataSource = optFriendLink.GetModelList(0);
gvFriendLink.DataBind();
}
3. 手写删除事件

做删除操作,我们只要编写RowDeleting事件就可以:

 代码如下 复制代码
protected void gvFriendLink_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(gvFriendLink.Rows[e.RowIndex].Cells[1].Text);
optFriendLink.Delete(id);
FetchData();
}
4. 获取主键的办法

细心的童鞋会发现,在刚才的删除事件中,我获取主键的方法非常傻逼,居然是直接访问Cells[1],也就是第二个单元格的值。但很多时候,项目里要求GridView上不能显示数据库中的主键字段,怎么办呢?

其实GridView自带访问主键的属性,叫做DataKey。

为了用这个属性,你首先得给GridView指定一个DataKeyName

image

然后在代码里你就可以访问某行对应的主键了:

 代码如下 复制代码
int id = Convert.ToInt32(gvFriendLink.DataKeys[e.RowIndex].Value);
5. GridView中选取某行的操作

我的友情链接模块没有这个需求,所以给贴一个以前做的选课系统里的例子:

 代码如下 复制代码
protected void gvCourses_SelectedIndexChanged(object sender, EventArgs e)
{
int userId = uid;
int courseId = Convert.ToInt32(gvCourses.SelectedRow.Cells[0].Text);
dalUca.Add(new Course.Model.UserCourseAssociation() { UserId = userId, CourseId = courseId });
FetchAllCourse();
FetchUserCourse(userId);
}
其实就是一个SelectedIndexChanged事件。但前提是你的GridView里必须有某个按钮可以触发这个事件:

一般是一个Select Command:

 代码如下 复制代码
<asp:CommandField ShowSelectButton="True" />

热门栏目