如何更改gridview所选项目背景颜色?

时间:2012-04-22 14:41:21

标签: asp.net

如何在Asp.net Web应用程序中更改gridview选定的项目背景颜色?

2 个答案:

答案 0 :(得分:2)

您可以在GridView标记下的aspx页面中执行此操作:

<SelectedRowStyle BackColor="Orange" />  

但是如果您想在鼠标悬停或鼠标移出时使用不同颜色,请在RowDataBound事件背后的代码中尝试以下内容

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

如果您想在不点击按钮的情况下选择行,请查看此链接:ASP.NET: Selecting a Row in a GridView

答案 1 :(得分:0)

您可以尝试在onmouseover事件上调用javascript函数。 This website有一个简单的例子:

在服务器端:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onmouseover"] =
            "javascript:mouseovercolor(this);";
        e.Row.Attributes["onmouseout"] =
            "javascript:mouseoutcolor(this);";
    }
}

在客户端:

<script language=javascript type="text/javascript">
    function mouseovercolor(mytxt) {
        mytxt.bgColor = 'Orange';
    }
    function mouseoutcolor(mytxt) {
        element.bgColor = 'White';
    }
</script>

已修改 This site has a nice example如何使其与onClick事件一起使用:

服务器端:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e){
  if (e.Row.RowType == DataControlRowType.DataRow){
    // javascript function to call on row-click event
    e.Row.Attributes.Add("onClick", "javascript:void SelectRow(this);");
  }
 }

客户方:

<script type="text/javascript">
         // format current row
         function SelectRow(row) {
             var _selectColor = "#303030";
             var _normalColor = "#909090";
             var _selectFontSize = "3em";
             var _normalFontSize = "2em";
             // get all data rows - siblings to current
             var _rows = row.parentNode.childNodes;
             // deselect all data rows
             try {
                 for (i = 0; i < _rows.length; i++) {
                     var _firstCell = _rows[i].getElementsByTagName("td")[0];
                     _firstCell.style.color = _normalColor;
                     _firstCell.style.fontSize = _normalFontSize;
                     _firstCell.style.fontWeight = "normal";
                 }
             }
             catch (e) { }
             // select current row (formatting applied to first cell)
             var _selectedRowFirstCell = row.getElementsByTagName("td")[0];
             _selectedRowFirstCell.style.color = _selectColor;
             _selectedRowFirstCell.style.fontSize = _selectFontSize;
             _selectedRowFirstCell.style.fontWeight = "bold";
         }
</script>