GridView的RowCommand事件中如何得到主键值及子控件

 GridView的RowCommand事件,当CommandName不是gridview 默认的三种命令名时,对表格的操作需触发RowCommand事件

UI代码:

代码
< asp:GridView ID = " grdResult "  runat = " server "  CssClass = " DataGrid_Container "  AllowPaging = " False "     
   AutoGenerateColumns
= " False "  BorderWidth = " 0 "   OnRowDataBound = " grdResult_RowDataBound "  DataKeyNames = " PlanId "    >    
   
< RowStyle CssClass = " DataGrid_Item "   />    
  
    < Columns >  
       
< asp:TemplateField  HeaderText = " 名称 "  HeaderStyle - HorizontalAlign = " Left "  ItemStyle - HorizontalAlign = " Left "   >    
         
< ItemTemplate   >                  
          
< asp:HyperLink ID = " DocName "  Text = ' <%# Eval("DocName") %> '  runat = " server " ></ asp:HyperLink >    
         
</ ItemTemplate >    
       
</ asp:TemplateField >  
     
< asp:TemplateField HeaderText = " 执行操作 " >
       
< ItemTemplate >
          
< asp:LinkButton id = " lbtToRun "  runat = " server "  CommandName = " cmdToRun "  CommandArgument = ' <%# Eval("PlanID")%> ' ></ asp:LinkButton >
          
< asp:HiddenField id = " hidUserName "  runat = " server "  Value = ' <%#Eval("UserName") %> ' ></ asp:HiddenField >
          
</ ItemTemplate >
        
</ asp:TemplateField >                            
     
</ Columns >                  
</ asp:GridView >   

 

假如在C# RowCommand事件中,我们要找到当前行的隐藏域hidUserName的值和Gridview的DataKey,被注释部分代码是错误的方法,在能用RowCommand事件中

代码

  protected   void  grdResult_RowCommand( object  sender, GridViewCommandEventArgs e)
 {
     
if  (e.CommandName  ==   " cmdToRun " ) // 控制
      {
          
// PlanID 为Key值
          
// 下面被注释掉的方法找不到隐藏域hidUserName
          
// HiddenField hidUserName = (HiddenField)grdResult.SelectedRow.FindControl("hidUserName");            
          HiddenField hidUserName  =  (HiddenField)((Control)e.CommandSource).FindControl( " hidUserName " );
          
// 下面被注释掉的方法找不到DataKeys
          
// string strid = grdResult.DataKeys[grdResult.SelectedIndex].Value.ToString();
           string  strid  =  e.CommandArgument.ToString();
          
// 下面可以执行你要的操作
          
AgentController.UpdateTable(hiduserName.value,strid);
        }
  }

 

 

你可能感兴趣的:(GridView)