JS控制GridView行选择
ASP.NET里的GridView控件使用非常广泛,虽然其功能强大,但总有一些不尽如人意的地方。
比如在选择行的时候,它就没有UltraWebGrid做的友好;UltraWebGrid允许用户设置是否显示选择框,设置允许,则会在最左边多出一列,表示选择的行。而GridView则没有这个功能。但没有,不代表不能实现,下面我就通过JS来实现行选择的标识。
后台代码:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
...{
int id = Convert.ToInt32(InstallandMaintanceGrid.DataKeys[e.Row.RowIndex].Value.ToString());
e.Row.Attributes.Add("ondblclick", "javascript:dbClick(" + id + ")");
e.Row.Attributes.Add("id", _i.ToString());
e.Row.Attributes.Add("onKeyDown", "SelectRow();");
e.Row.Attributes.Add("onClick", "MarkRow(" + _i.ToString()+","+id + ");");
_i++;
}
...{
int id = Convert.ToInt32(InstallandMaintanceGrid.DataKeys[e.Row.RowIndex].Value.ToString());
e.Row.Attributes.Add("ondblclick", "javascript:dbClick(" + id + ")");
e.Row.Attributes.Add("id", _i.ToString());
e.Row.Attributes.Add("onKeyDown", "SelectRow();");
e.Row.Attributes.Add("onClick", "MarkRow(" + _i.ToString()+","+id + ");");
_i++;
}
前台代码:
<script type="text/javascript">
function dbClick(keys)...{
//双击,获取该行ID
document.getElementById("ctl00_hd_selectedid").value = keys;
}
var currentRowId = 0;
function SelectRow()//选择行
...{
if (event.keyCode == 40)
MarkRow(currentRowId+1);
else if (event.keyCode == 38)
MarkRow(currentRowId-1);
}
function MarkRow(rowId,keys)//选中行变色
...{
if (document.getElementById(rowId) == null)
return;
if (document.getElementById(currentRowId) != null )
...{
document.getElementById(currentRowId).style.backgroundColor ='#ffffff';
}
currentRowId = rowId;
document.getElementById(rowId).style.backgroundColor = '#ff0000';
document.getElementById("ctl00_hd_selectedid").value = keys;
}
</script>
function dbClick(keys)...{
//双击,获取该行ID
document.getElementById("ctl00_hd_selectedid").value = keys;
}
var currentRowId = 0;
function SelectRow()//选择行
...{
if (event.keyCode == 40)
MarkRow(currentRowId+1);
else if (event.keyCode == 38)
MarkRow(currentRowId-1);
}
function MarkRow(rowId,keys)//选中行变色
...{
if (document.getElementById(rowId) == null)
return;
if (document.getElementById(currentRowId) != null )
...{
document.getElementById(currentRowId).style.backgroundColor ='#ffffff';
}
currentRowId = rowId;
document.getElementById(rowId).style.backgroundColor = '#ff0000';
document.getElementById("ctl00_hd_selectedid").value = keys;
}
</script>
--------------------- 本文来自 zsj830120 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/zsj830120/article/details/2408422?utm_source=copy