zoukankan
html css js c++ java
GridView中使用DataKeyNames存储数据键值
很多时候我们需要在
GridView的
RowCommand
之类的事件中需要获取当前行的一些关联性的数据值。但这些数据值又没有直接体现在GridView的列中。这个时候该怎么办呢?
有同学喜欢用隐藏列的方式,把需要使用但不显示的字段绑定到此列上,同时设置列宽为0或不显示,使用时可以用常规的取某行某列的方式来获取数据。
但是在Framework 2.0中,我们可以采用DataKeyNames的方式来获取此类数据。
代码示例:
(前台)
<
asp:GridView ID
=
"
GridView1
"
runat
=
"
server
"
DataKeyNames
=
"
Grup
"
OnRowCommand
=
"
GridView1_RowCommand
"
AutoGenerateColumns
=
"
False
"
>
<
Columns
>
<
asp:TemplateField
>
<
ItemTemplate
>
<
asp:Label ID
=
"
Label1
"
runat
=
"
server
"
Text
=
'
<%#Eval("GrupName") %>
'
></
asp:Label
>
</
ItemTemplate
>
</
asp:TemplateField
>
<
asp:ButtonField Text
=
"
按钮
"
/>
</
Columns
>
</
asp:GridView
>
Grup
为我们想使用但不需要显示的列。(如果有多个字段,使用逗号分开)
(后台)
protected
void
Page_Load(
object
sender, EventArgs e)
{
if
(
!
IsPostBack )
{
DataTable dt
=
new
DataTable();
dt.Columns.Add(
"
Grup
"
);
dt.Columns.Add(
"
GrupName
"
);
dt.Rows.Add(
new
object
[]
{
0
,
"
营业部
"
}
);
dt.Rows.Add(
new
object
[]
{
1
,
"
市场部
"
}
);
this
.GridView1.DataSource
=
dt;
this
.GridView1.DataBind();
}
}
protected
void
GridView1_RowCommand(
object
sender, GridViewCommandEventArgs e)
{
//
获取当前行索引
int
index
=
Convert.ToInt32(e.CommandArgument);
//
取出当前行数据键值对象中的值
string
strGrup
=
((GridView)sender).DataKeys[index].Values[
"
Grup
"
].ToString();
}
顺便补充一句。
如果你使用模板列中放置按钮控件的方式,要想在按钮事件中获取这种字段值就更简单了。
只需要在按钮的CommandArgument属性设置为想绑定的字段,如:
<
asp:TemplateField
>
<
ItemTemplate
>
<
asp:Button
ID
="Button2"
runat
="server"
OnClick
="Button2_Click"
Text
="Button"
CommandArgument
='
<%#Eval("Grup") %
>
' />
</
ItemTemplate
>
</
asp:TemplateField
>
按钮事件中如是写:
protected
void
Button2_Click(
object
sender, EventArgs e)
{
string
strGrup
=
((Button)sender).CommandArgument.ToString();
}
Austin Liu 刘恒辉
Lzhdim Group's Chairman,Project Manager and Software Designer
E-Mail:
lzhdim@163.com
Blog:
http://lzhdim.cnblogs.com
欢迎收藏和转载此博客中的博文,但是请注明出处,给作者一个与大家交流的空间。谢谢大家。
查看全文
相关阅读:
Python3 日期与时间戳相互转换
PHP 二维数组排序保持键名不变
C# Command命令(行为型模式)+队列 实现事务,带异步命令重试机制和生命周期
领域驱动系列五模型驱动设计的构造块
领域驱动系列四之模型驱动
领域驱动系列三
领域驱动系列二策略模式的应用
领域驱动系列一基本概念介绍
Redis学习系列七分布式锁
Redis学习系列六ZSet(有序列表)及Redis数据结构的过期
原文地址:https://www.cnblogs.com/lzhdim/p/1391759.html
最新文章
简单堆排序
gdbserver 移植与多线程调试
多线程死锁调试小技巧
MySQL 存储过程/游标/事务
iscsi target 之LIO配置
Python之包管理工具
iscsi target 研究
librbd 分析
Ceph BlueFS
linux 文件系统工作原理
热门文章
ceph iscsi (SCST)
防盗链之URL参数签名 总结
ajax请求window.open()被拦截
Python json序列化
python assert的用处
Python中使用type、metaclass动态创建方法和属性
Python中使用枚举类
Python 中@property的用法
Python动态绑定属性slots的使用
Python 私有变量的访问和赋值
Copyright © 2011-2022 走看看