Vishweshwar Kapse
Vishweshwar Kapse

Reputation: 939

Changing color of selected row in asp.net gridview

Hi i am trying to change the color of the selected row in the asp.net gridview i have defined my grid view like this

<asp:GridView ID="gridContractor" runat="server" AllowPaging="True" AllowSorting="True"
                AutoGenerateColumns="False" CssClass="GridViewStyle" GridLines="None" EnableModelValidation="True"
                DataKeyNames="DeviceID" OnRowCommand="gridContractor_RowCommand" OnPageIndexChanging="gridContractor_PageIndexChanging"
                Width="100%" EmptyDataText = "No records to display" EmptyDataRowStyle-HorizontalAlign="Center">
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                    <asp:BoundField HeaderText="Device IMEI" DataField="DeviceID" Visible="false">
                        <HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" />
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="175" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="Person Name" DataField="PersonName">
                        <HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" />
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="#Observations" DataField="GpsPointsCount" ControlStyle-Width="50px">
                        <HeaderStyle HorizontalAlign="Right" VerticalAlign="Middle" />
                        <ItemStyle HorizontalAlign="Right" VerticalAlign="Middle" Width="50" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="#Violations" DataField="ViolationCount" ControlStyle-Width="60px">
                        <HeaderStyle HorizontalAlign="Right" VerticalAlign="Middle" />
                        <ItemStyle HorizontalAlign="Right" VerticalAlign="Middle" Width="60" />
                    </asp:BoundField>
                    <asp:TemplateField HeaderText="" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="50">
                        <ItemTemplate>
                            <asp:Button ID="btnEdit" runat="server" Text="View" CommandName="View" Enabled="true" OnClick="btn_GrdClick"
                                CommandArgument="<%#Bind('DeviceID') %>" />
                        </ItemTemplate>
                        <HeaderStyle Width="50" />
                        <ItemStyle HorizontalAlign="Center"></ItemStyle>
                    </asp:TemplateField>
                </Columns>
                <RowStyle CssClass="RowStyle" />
                <EmptyDataRowStyle CssClass="EmptyRowStyle" />
                <PagerStyle CssClass="PagerStyle" />
                <SelectedRowStyle BackColor="AliceBlue" />
                <HeaderStyle CssClass="HeaderStyle" />
                <EditRowStyle CssClass="EditRowStyle" />
                <AlternatingRowStyle CssClass="AltRowStyle" />
            </asp:GridView>

and i have handled the button click event the problem is that each time i am selecting a row the previous row color is not getting changed even though i am doing it. once clicked the row remains yellow can somebody help me please

my aspx.cs code

 protected void btn_GrdClick(object sender, EventArgs e)
    {
        GridViewRow PreviousRow = Session["PreviousRow"] as GridViewRow;
        if (PreviousRow != null)
            PreviousRow.ForeColor = Color.White;
        GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
        row.ForeColor = Color.Yellow;
        Session["PreviousRow"] = row;
    }

Upvotes: 2

Views: 48048

Answers (7)

Fernando Meneses Gomes
Fernando Meneses Gomes

Reputation: 867

protected void gridName_RowCommand(object sender, GridViewCommandEventArgs e)
{
        if (e.CommandName == "xxx")
        {
            foreach (GridViewRow rx in gridName.Rows)
            {
                rx.ForeColor = Color.White;
            }

            ((System.Web.UI.WebControls.TableRow)((System.Web.UI.Control)e.CommandSource).DataItemContainer).ForeColor = Color.Yellow;
        }
}

cheers

Upvotes: 0

Atters
Atters

Reputation: 821

I was looking for a solution to this problem and then saw a couple of threads like this mentioning that you need to track the selected row in the session. Whilst this may be true for a full postback when it's partial I found a better solution using Css.

Gridview is in an update panel, the surrounding div has a class=grid and the gridview has class=datatable then the following elements are defined within the Gridview;

RowStyle CssClass="item-row"

SelectedRowStyle CssClass="selectedItem-row"

Then the associated css looks like this;

    .grid .datatable .item-row TD {
        border-bottom: #bbd9ee 1px solid;
        text-align: left;
        padding-bottom: 6px;
        padding-left: 4px;
        padding-right: 4px;
        font-size: 0.7em;
        border-top: #bbd9ee 1px solid;
        padding-top: 6px;
    }

        .grid .datatable .item-row TD.highlightcell {
            background-color: #fffacd;
            color: #000;
        }

    .grid .datatable .item-row:hover {
        background-color: #fffacd;
        color: #000;
    }

    .grid .datatable .selectedItem-row TD {
        border-bottom: #bbd9ee 1px solid;
        text-align: left;
        padding-bottom: 6px;
        padding-left: 4px;
        padding-right: 4px;
        font-size: 0.7em;
        border-top: #bbd9ee 1px solid;
        padding-top: 6px;
        background-color: #d7ffcd;
    }

Upvotes: 1

user1760979
user1760979

Reputation:

Use GridView Load Event

I have given example of my code,

Protected Sub grvaddbook_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles grvaddbook.Load
    Dim row1 As GridViewRow
    row1 = grvaddbook.HeaderRow
    Dim i As Integer
    i = 0
    For Each row As GridViewRow In grvaddbook.Rows
        Dim main As Label = DirectCast(grvaddbook.Rows(i).Cells(0).FindControl("lblismain"), Label)

        If main.Text = 1 Then
            Dim lbtnmakedefault As LinkButton = DirectCast(grvaddbook.Rows(i).Cells(0).FindControl("lbtnmakedefault"), LinkButton)
            lbtnmakedefault.Visible = False
            mainaid = DirectCast(grvaddbook.Rows(i).Cells(0).FindControl("lblaid"), Label).Text
        End If
        i = i + 1
    Next
End Sub

Upvotes: 0

Hiren
Hiren

Reputation: 41

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    GridView1.SelectedRow.BackColor = System.Drawing.Color.White;
}

Upvotes: 4

bazz
bazz

Reputation: 613

1) First thing you need to do is to handle the Grid's RowCommand event, protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e). What you are doing is treating button's click event separate to the gridview's command event. 2) you can assign an index to the command argument, and change the row's colour and set all the other rows to the default colour. One example can be found here

Hope this helps,

Upvotes: 0

nunespascal
nunespascal

Reputation: 17724

GridViewRow is a control. Like every object on the page, it will be created during the page life cycle.
The reference you hold in Session is to the object created during the last request.

To solve the problem, keep only the index(or key) of the row in Session and use that to change the color of previous row.

protected void btn_GrdClick(object sender, EventArgs e)
{
    if(Session["PreviousRowIndex"] != null)
    {
      var previousRowIndex = (int)Session["PreviousRowIndex"];
      GridViewRow PreviousRow = MyGridView.Rows[previousRowIndex];
      PreviousRow.ForeColor = Color.White;
    }

    GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
    row.ForeColor = Color.Yellow;
    Session["PreviousRowIndex"] = row.RowIndex;
}

Upvotes: 4

Jalpesh Vadgama
Jalpesh Vadgama

Reputation: 14256

try something like below.

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='yellow'");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");
    }
}

Upvotes: 1

Related Questions