2

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

4

2 回答 2

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

于 2012-04-22T14:47:13.157 回答
0

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

在服务器端:

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>

编辑: 这个网站有一个很好的例子,说明如何使它与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>
于 2012-04-22T14:59:03.823 回答