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

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

protected void gvMain_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string strGvName = "gvMain";
e.Row.Attributes.Add("id", strGvName + _i.ToString());
e.Row.Attributes.Add("onKeyDown", "SelectRow(event,'" + strGvName + "');");
e.Row.Attributes.Add("onClick", "MarkRow(" + _i.ToString() + ",'" + strGvName + "');");
e.Row.Attributes.Add("tabindex", "0");
_i++;
}
}

其中的_i要预先声明

private int _i = 0;

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

 

在html中加入js语句

<mce:script type="text/javascript" language="javascript"><!--
var currentRowId=0;
function SelectRow(ev,strGvName)
{
var e = window.event || ev;
var keyCode = -1;
if (e.which == null)
keyCode= e.keyCode; // IE
else
if (e.which > 0)
keyCode=e.which; // All others
if (keyCode==40)
MarkRow(currentRowId+1,strGvName);
if (keyCode==38)
MarkRow(currentRowId-1,strGvName);
}
function MarkRow(rowId,strGvName)
{
if (document.getElementById(strGvName+rowId) == null)
return;
if (document.getElementById(strGvName+currentRowId) != null )
document.getElementById(strGvName+currentRowId).style.backgroundColor = '#ffffff';
currentRowId = rowId;
document.getElementById(strGvName+rowId).style.backgroundColor = '#E6F5FA';
var obj=document.getElementById(strGvName);
obj.rows[rowId].cells[0].focus();
}
// --></mce:script>


 

posted @   星火燎猿*  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
点击右上角即可分享
微信分享提示