在gridview上实现上下键移动选中行!

在gridview上实现上下键移动选中行!       

http://blog.csdn.net/gdsimon/article/details/6121424

因为要用到js,所以要在gridview的OnRowDataBound中加入js的语句。

  1. protectedvoid gvMain_OnRowDataBound(object sender, GridViewRowEventArgs e) 
  2.     if (e.Row.RowType == DataControlRowType.DataRow) 
  3.     { 
  4.         string strGvName = "gvMain"
  5.         e.Row.Attributes.Add("id", strGvName + _i.ToString()); 
  6.         e.Row.Attributes.Add("onKeyDown", "SelectRow(event,'" + strGvName + "');"); 
  7.         e.Row.Attributes.Add("onClick", "MarkRow(" + _i.ToString() + ",'" + strGvName + "');"); 
  8.         e.Row.Attributes.Add("tabindex", "0"); 
  9.         _i++; 
  10.     } 

其中的_i要预先声明

private int _i = 0;

为什么要加入tabindex="0"这个属性呢,没有这个的话IE里可以运行正常,但firefox或chrome这些浏览器就不行了 。

在html中加入js语句

  1. <mce:script type="text/javascript" language="javascript"><!-- 
  2.     var currentRowId=0; 
  3.     function SelectRow(ev,strGvName) 
  4.     { 
  5.         var e = window.event || ev; 
  6.         var keyCode = -1; 
  7.         if (e.which == null
  8.             keyCode= e.keyCode;    // IE 
  9.         else  
  10.             if (e.which > 0) 
  11.                 keyCode=e.which;    // All others 
  12.          if (keyCode==40) 
  13.             MarkRow(currentRowId+1,strGvName); 
  14.          if (keyCode==38) 
  15.             MarkRow(currentRowId-1,strGvName); 
  16.     } 
  17.     function MarkRow(rowId,strGvName) 
  18.     { 
  19.         if (document.getElementById(strGvName+rowId) == null
  20.             return;            
  21.         if (document.getElementById(strGvName+currentRowId) != null
  22.             document.getElementById(strGvName+currentRowId).style.backgroundColor = '#ffffff'
  23.         currentRowId = rowId; 
  24.         document.getElementById(strGvName+rowId).style.backgroundColor = '#E6F5FA'
  25.         var obj=document.getElementById(strGvName); 
  26.         obj.rows[rowId].cells[0].focus(); 
  27.     }   
  28.  
  29. -></mce:script> 
原文地址:https://www.cnblogs.com/tabcdt/p/2756546.html