65.9K
CodeProject 正在变化。 阅读更多。
Home

单击时更改 GridView 行颜色,无需回发

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.17/5 (16投票s)

2008年3月19日

CPOL
viewsIcon

164111

downloadIcon

1263

关于在鼠标单击时更改 GridView 行颜色而不进行回发的文章。

引言

本文介绍如何在页面无需回发的情况下,通过鼠标点击更改 GridView 行的颜色。为了实现这一点,我们将使用一些 javascript 以及 GridView 控件本身 :).

背景

GridView 是一个服务器端控件,包含行和列。在某些情况下,我们希望根据应用程序的功能/UI 要求,实现 GridView 控件的更高级功能,而不仅仅是其直接的功能。

使用代码

以下 javascript 将用于更改行的颜色。

        <script type="text/javascript">
        //variable that will store the id of the last clicked row
        var previousRow;
        
        function ChangeRowColor(row)
        {
            //If last clicked row and the current clicked row are same
            if (previousRow == row)
                return;//do nothing
            //If there is row clicked earlier
            else if (previousRow != null)
                //change the color of the previous row back to white
                document.getElementById(previousRow).style.backgroundColor = "#ffffff";
            
            //change the color of the current row to light yellow

            document.getElementById(row).style.backgroundColor = "#ffffda";            
            //assign the current row id to the previous row id 
            //for next row to be clicked
            previousRow = row;
        }
     </script>

以下代码需要在 GridView1_RowDataBound 事件中实现

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
        Handles GridView1.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            e.Row.Attributes.Add("onclick", "javascript:ChangeRowColor('" & e.Row.ClientID & "')")
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'FillDataTable is a function that will return a DataTable
            'with some values and is available in the code for download.
            Me.GridView1.DataSource = Me.FillDataTable()
            Me.GridView1.DataBind()
        End If
    End Sub
        

点击行之前

点击行之后

© . All rights reserved.