.net – gridview highlighting current row

asp.netnetvb.net

Is there a built-in method of highlighting the currently selected row in a gridview?

Each row in my gridview has a button (via a buttonField). When the user presses this button, the background color changes…I do it like this:

Protected Sub gvTransferOwner_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvTransferOwner.RowCommand
    If e.CommandName = "Select" Then
        Dim index As Integer = Convert.ToInt32(e.CommandArgument)
        Dim selectedRow As GridViewRow = gvTransferOwner.Rows(index)
        selectedRow.Style.Add("background-color", "#ffcccc")
    End If
End Sub

This highlights the row, but once the user presses the button in another row, it still retains that color in all previously-pressed rows.

Is there a way so that only one row at a time(the currently selected row) is highlighted?

Thanks

Best Answer

If you use a global variable to store the index of the row that is being selected, you can change that row back to the original color whenever a new row is selected.

Dim previousSelected As Integer 'global variable to store the last selected index
Protected Sub gvTransferOwner_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvTransferOwner.RowCommand
    If e.CommandName = "Select" Then
        Dim index As Integer = Convert.ToInt32(e.CommandArgument)
        Dim selectedRow As GridViewRow = gvTransferOwner.Rows(previousSelected)
        selectedRow.Style.Add("background-color", "#ffffff") 'change it back to original color
        selectedRow = gvTransferOwner.Rows(index)
        selectedRow.Style.Add("background-color", "#ffcccc") 'change the color of the new row
        previousSelected = index
    End If
End Sub
Related Topic