Friday, March 25, 2011

Highliting Row in DataGrid on mouse over and adding row click eventt to gridview

Here is the example for adding mouseover effect and also adding row click event to the grid rows.

Aspx page with code behind:
<%@ Page Language="C#" %> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<script runat="server">  
  
    protected void grvContact_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
        if (e.Row.RowType == DataControlRowType.DataRow) 
        { 
            e.Row.Attributes.Add("onmouseover""this.style.backgroundColor='#aaaaaa';this.style.cursor='hand'"); 
            e.Row.Attributes.Add("onmouseout""this.style.backgroundColor='ffffff';"); 
            e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(this.grvContact, "Select$" + e.Row.RowIndex)); 
        } 
    } 
 
    //this code to avoid the validation request issue
    protected override void Render(HtmlTextWriter writer) 
    { 
        for (int i = 0; i < this.grvContact.Rows.Count; i++) 
        { 
            ClientScript.RegisterForEventValidation(this.grvContact.UniqueID, "Select$" + i); 
        } 
        base.Render(writer); 
    } 
 
    protected void grvContact_SelectedIndexChanged(object sender, EventArgs e) 
    { 
        Label1.Text = "Row with the contact ID <b>" + this.grvContact.SelectedDataKey.Value.ToString() + " </b> clicked."; 
    } 
</script> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
        <asp:GridView ID="grvContact" runat="server" DataSourceID="SqlDataSource2" DataKeyNames="ContactID" 
            AutoGenerateColumns="False" 
            AllowPaging="true" OnRowDataBound="grvContact_RowDataBound"  
            onselectedindexchanged="grvContact_SelectedIndexChanged"> 
            <Columns> 
                <asp:BoundField DataField="ContactID" HeaderText="ContactID" /> 
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" /> 
                <asp:BoundField DataField="MiddleName" HeaderText="MiddleName" /> 
                <asp:BoundField DataField="LastName" HeaderText="LastName" /> 
            </Columns> 
        </asp:GridView> 
    </div> 
    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" 
        SelectCommand="SELECT TOP 100 [ContactID], [FirstName], [MiddleName], [LastName] FROM [AdventureWorks].[Person].[Contact]"> 
    </asp:SqlDataSource> 
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> 
    </form> 
</body> 
</html>

No comments:

Post a Comment