在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>


 

 

你可能感兴趣的:(GridView)