views:

995

answers:

1

I have a Gridview with alternating row colors and want to highlight a row when its clicked anywhere on that row. Unfortunaly, the code that I found and am using applies the darker color shade to the previously clicked row. For example, If out of a 4 row gridview, 2 and 4 are shaded silver, while the other 2 are white. If I click on row 1, then click on row 4, row 1 is now shaded silver. This also happens if I click on any other row. Here is my code:

protected void CCAGridView_OnRowCreated(object sender, GridViewRowEventArgs e)
 {
  if (e.Row.RowType == DataControlRowType.DataRow)
   e.Row.Attributes.Add("onclick", "HilightRow(this)");
 }

<asp:GridView ID="GridView" runat="server"  HeaderStyle-Width="200" HeaderStyle-BackColor="#2B6292" HeaderStyle-ForeColor="White" 
 AllowSorting="true" AllowPaging="true" Width="600" AutoGenerateColumns="False" OnRowCreated="GridView_OnRowCreated" 
 DataKeyNames="Id" AlternatingRowStyle-BackColor="Silver" BorderColor="#2B6292" BorderWidth="1" BorderStyle="solid">
        <Columns>
         ...
        </Columns>
    </asp:GridView>

Any help would be appreciated. Thanks.

Also, would anyone be able to help me find what row is highlighted, server side? Like a select.

A: 

Well, I can help with how to find the selected row assuming you know the primary key. In your RowDataBound event, you can get the DataItem (cast it to the real type) and then compare it to the value you are looking for (then highlight it). I had to turn off the alternatingRowSTyle to make this work. Don't know much about that.

protected void Page_Load(object sender, EventArgs e) { GridViewCompany.AlternatingRowStyle.Reset(); GridViewCompany.SelectedRowStyle.Reset(); }

    protected void GridViewCompany_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        int selectedCompanId = Convert.ToInt32(StateService.I.Get(CookieIdType.CompanySelected));
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var userResult = e.Row.DataItem as CompanyResult;
            if (userResult != null)
            {
                if (userResult.Id == selectedCompanId)
                {
                    e.Row.BackColor = Color.LightGray;
                }
            }
        }
    }
Peter Kellner