ASP.NET中GridView实现行鼠标滑过及选择变色

一、鼠标滑过变色

只要要给GridView添加OnRowDataBound方法即可。

前台代码: 前台代码:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView_RowDataBound">
</asp:GridView>
后台代码: 后台代码:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
	//判断是否为数据行(排除标题行)
	if (e.Row.RowType == DataControlRowType.DataRow)
	{
		e.Row.Attributes.Add("onmouseover", "col=this.style.backgroundColor;this.style.backgroundColor=#95B8FF");
		e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=col");
	}
}


protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) { //判断是否为数据行(排除标题行) if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onmouseover", "col=this.style.backgroundColor;this.style.backgroundColor=#95B8FF"); e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=col"); } }

二、鼠标单击(双击)变色

同上,后台代码稍作修改即可,若要双击变色只要将onclick改为ondblclick即可

后台代码:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
	//判断是否为数据行(排除标题行)
	if (e.Row.RowType == DataControlRowType.DataRow)
	{
		e.Row.Attributes.Add("onclick", "if(window.oldtr!=null){window.oldtr.style.backgroundColor=oldc;}oldc=this.style.backgroundColor;this.style.backgroundColor=#e6c5fc;window.oldtr=this;");
	}
}

三、同时实现以上变色

后台代码:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
	//判断是否为数据行(排除标题行)
	if (e.Row.RowType == DataControlRowType.DataRow)
	{
		e.Row.Attributes.Add("onmouseover", "if(window.oldtr==null||window.oldtr!=this){col=this.style.backgroundColor;this.style.backgroundColor=#95B8FF}");
		e.Row.Attributes.Add("onmouseout", "if(window.oldtr==null||window.oldtr!=this){this.style.backgroundColor=col}");
		e.Row.Attributes.Add("onclick", "if(window.oldtr!=null){window.oldtr.style.backgroundColor=oldc;}this.style.backgroundColor=#e6c5fc;window.oldtr=this;oldc=col;");
	}
}


二、鼠标单击(双击)变色 同上,后台代码稍作修改即可,若要双击变色只要将onclick改为ondblclick即可 后台代码: protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) { //判断是否为数据行(排除标题行) if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onclick", "if(window.oldtr!=null){window.oldtr.style.backgroundColor=oldc;}oldc=this.style.backgroundColor;this.style.backgroundColor=#e6c5fc;window.oldtr=this;"); } } 三、同时实现以上变色 后台代码: protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) { //判断是否为数据行(排除标题行) if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onmouseover", "if(window.oldtr==null||window.oldtr!=this){col=this.style.backgroundColor;this.style.backgroundColor=#95B8FF}"); e.Row.Attributes.Add("onmouseout", "if(window.oldtr==null||window.oldtr!=this){this.style.backgroundColor=col}"); e.Row.Attributes.Add("onclick", "if(window.oldtr!=null){window.oldtr.style.backgroundColor=oldc;}this.style.backgroundColor=#e6c5fc;window.oldtr=this;oldc=col;"); } }
经验分享 程序员 微信小程序 职场和发展