昨天在用GridView想实现如DataGrid 的功能,即在对GridView的数据源邦定时,其中要实现有几列隐藏,但在GridView的RowCommand函数中,和在DataGrid的处理一样,通过e来过的隐藏列的值。
但在实践中发现,在GridView的RowCommand函数中,他不能像DataGrid一样通过e.item获得那一列的值,更别说获得获得隐藏列的值。因为在GridView的RowCommand函数中没有e.item这样的功能,后来在网上查找相关信息才知道,你需要通过e.CommandArgument来获得你需要的参数,再通过该参数来获得相应的值。而CommandArgument是在GridView的RowCreated函数中设定的,如在GridView中有一个“详情”的LinkButton,在RowCreated中,你需要设置该LinkButton的CommanArgurment,设置例子参看如下代码:
protected void GridView1_RowCreated( object sender, GridViewRowEventArgs e)
... {
if (e.Row.RowType == DataControlRowType.DataRow)
...{
LinkButton btn = (LinkButton)e.Row.Cells[e.Row.Cells.Count - 1].Controls[0];
btn.CommandArgument = e.Row.RowIndex.ToString();//this.GridView1.Rows[e.Row.RowIndex].Cells[0].ToString();
}
}
然后在RowCommand函数中获得CommandArgument的值,然后根据其获得的值再获得具体相应的值。
然而,若你的GridView中存在一些隐藏列,你就不能通过GridViewItem.cells[index]来获得其值,我也不知道GridView中为什么要这样做,但通过如下方法你可以获得其值:
在GridView的DataKeyName属性中,将你需要隐藏的列的值设置其中,然后再在RowCommand中获得其值,餐卡代码如下:
// 在GirdView中设置的参数
< asp:GridView ID = " GridView1 " runat = " server " AutoGenerateColumns = " False " AllowPaging = " True "
OnPageIndexChanging = " GridView1_PageIndexChanging " PageSize = " 20 " OnRowCommand = " GridView1_RowCommand "
OnRowCreated = " GridView1_RowCreated "
DataKeyNames = " UserID,JobID,DptID " >
< Columns >
< asp:BoundField DataField = " DptName " HeaderText = " 部门 " />
< asp:BoundField DataField = " Banzhu " HeaderText = " 班组 " />
< asp:BoundField DataField = " JobName " HeaderText = " 职位/岗位 " />
< asp:BoundField DataField = " TrueName " HeaderText = " 姓名 " />
< asp:BoundField DataField = " XiaoLingTong " HeaderText = " 小灵通 " />
< asp:BoundField DataField = " BanGongPhone " HeaderText = " 办公电话 " />
< asp:BoundField DataField = " ExtensionPhone " HeaderText = " 分机 " />
< asp:BoundField DataField = " TelePhone " HeaderText = " 手机 " />
< asp:BoundField DataField = " HousePhone " HeaderText = " 住宅电话 " />
< asp:BoundField DataField = " Remark " HeaderText = " 备注 " />
< asp:ButtonField CommandName = " Selects " Text = " 详情 " />
< asp:ButtonField CommandName = " Deletes " Text = " 删除 " />
</ Columns >
</ asp:GridView >
// 在该函数中,获得DataKeyName的属性值,其中Index就是在Row_Created中设置的参数
protected void GridView1_RowCommand( object sender, GridViewCommandEventArgs e)
... {
if (e.CommandName == "Selects")
...{
int index = int.Parse(e.CommandArgument.ToString());
GridViewItem item = this.GridView1.Rows[index];
//要获得其他置,通过item.Cells[cells_index].Text来获得,再次不过多说明,
//Datakey获得在DataKeyName设置的值
DataKey ky = this.GridView1.DataKeys[index];
this.Label1.Text += "UserID:" + ky["UserID"]+"<br>";
this.Label1.Text += "DptID:" + ky["DptID"] + "<br>";
this.Label1.Text += "JobID:" + ky["JobID"] + "<br>";
}
}
而且这样的方法,不会出现分页的效果失效。
这些只是我的一些处理办法,大家若有什么好的办法,大家请多指教,谢谢了,^_^