Yasserzaid’s Weblog

March 5, 2009

Highlighting a GridView Row When Clicking a CheckBox

Filed under: ASP.Net — yasserzaid @ 8:12 pm

Hi

try this example :-

<div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
            DataSourceID="SqlDataSource1" ForeColor="#333333" OnRowDataBound="GridView1_RowDataBound">
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
                <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
            </Columns>
            <RowStyle BackColor="#EFF3FB" />
            <EditRowStyle BackColor="#2461BF" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:Northwind %>"
            SelectCommand="SELECT [CategoryName], [Description] FROM [Categories]"></asp:SqlDataSource>
   
    </div>

in code behind :-

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if ((e.Row.RowType == DataControlRowType.DataRow))
        {
            StringBuilder script = new StringBuilder();
            script.Append("if (this.checked) {");
            script.Append("document.getElementById('");
            script.Append(e.Row.ClientID);
            script.Append("').style.backgroundColor='Blue';");
            script.Append("} else {");
            script.Append("document.getElementById('");
            script.Append(e.Row.ClientID);
            script.Append("').style.backgroundColor='';");
            script.Append("}");
            ((CheckBox)e.Row.Cells[0].FindControl("CheckBox1")).Attributes.Add("onclick", script.ToString());
        }

    }

Hope this helps

Good Luck

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.