zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

asp.netgridview的Rowcommand命令中获取行索引的方法总结

ASP方法索引命令 获取 总结 netGridview
2023-06-13 09:14:18 时间
一、通过命令源获取当前行索引。

方法比较多,GridView的Command事件中无法象DataGrid那样直接获取行,

法1,
GridViewRowdrv=((GridViewRow)(((Button)(e.CommandSource)).Parent.Parent));//CommandSource引起事件的命令源,(疑问,根据MSDN说的是GridView,如果这样的话这样操作是错误的,但我得到的确实正确的,那说明得到的是BUtton控件,等待以后查证).
drv.RowIndex


二、通过在RowDataBound事件中把行索引绑定到控件的CommandArgument

由于事件参数GridViewCommandEventArgs并不公开Row属性指示当前行,(DataGridCommandEventArgs公开Item属性以获取当然DataGridItem,不知ASP.NETTeam是如何考虑这一设计的),因此需要一点“技巧”来获取此属性。

其实这是一个早就已知的问题,鉴于CSDN里面每每有人疑惑,这里稍微整理下,便于参阅:

复制代码代码如下:

protectedvoidGridView1_RowCommand(objectsender,GridViewCommandEventArgse)
{
introwIndex=-1;
GridViewRowrow=null;
switch(e.CommandName)...{
case"Command1"://模板列
//对于模板列内的按钮,我们需要显示绑定行索引到按钮的CommandArgument属性
//以获取触发事件的行信息
rowIndex=Convert.ToInt32(e.CommandArgument);
row=GridView1.Rows[rowIndex];
DisplayInfo(row,e.CommandName);
//yourcodes
//
break;
case"Command2"://模板列
//同样处于模板列中,但不采用Command1方式,而是通过NamingContrainer属性
//直接获取当前的GridViewRow
ControlcmdControl=e.CommandSourceasControl;//表示触发事件的IButtonControl,保持统一性并便于后续操作,我们这里直接转化为控件基类Control
row=cmdControl.NamingContainerasGridViewRow;
DisplayInfo(row,e.CommandName);
//yourcodes
//
break;
case"Command3"://绑定列
//对于ButtonField列,数据源控件内部自动以适当的项索引值填充CommandArgument属性。
//而无需我们显示绑定其CommandArgument属性
//注意,我们这里无法采用Command2的方式,对于BUttonField触发的事件,
//GridViewCommandEventArgs.CommandSource表示的包含此按钮的GridView
rowIndex=Convert.ToInt32(e.CommandArgument);
row=GridView1.Rows[rowIndex];
DisplayInfo(row,e.CommandName);
//yourcodes
//
break;
}
}