对asp.net中gridview控件设置单击一行,行背景色改变,该行显示为选取状态,代码如下:
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onclick", "this.style.backgroundColor='#00A9FF'");
            }
        }
现在问题是,先单击第一行,背景色变为蓝色,再单击第二行,背景色也变为蓝色,但是原来第一行的背景色没有恢复成原来的白色,还是蓝色。怎样将原来行的背景色恢复成白色?

解决方案 »

  1.   

    现象分析:你添加的是 onclick 事件 这说明 点击行时 背景颜色改变 可是什么时候变回来呢? 你在代码中并没有设置,所以是这样的运行结果提供一个光棒效果的解决方案: if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='99ccff'");
                    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''");
                }
      

  2.   

    在js里用变量保存选中行。当单击后重新设置,把原来的背景清空。
    e.Row.Attributes.Add("onclick", "selectChange(this);");<script>
    var selectRow=null;
    function selectChange(row)
    {
        if(selectRow==row)
        {
            return;
        }
        if(selectRow!=null)
        {
           selectRow.style.backgroundColor="ffffff";
        }
        row.style.backgroundColor="99ccff";
        selectRow=row;
    }
    </script>
      

  3.   

    e.Row.Attributes.Add("onmouseover", "co=this.style.backgroundColor;this.style.backgroundColor='red';");
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor=co;");
      

  4.   


    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "temp=this.style.backgroundColor; this.style.backgroundColor='#FDEFCE'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=temp");
            }
        }
      

  5.   

    给个例子
    protected void gvPCInfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
             if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.BackColor != System.Drawing.Color.Red)
                {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'");//进改变色
                }
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#CCFFCC'");//出变原回的颜色
    }}
      

  6.   

    如果在gridview中设置的有隔行变色就有些麻烦了
      

  7.   


        /// <summary>
        /// 增加光棒效果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            { 
                e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#6699ff'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor");
            }
        }