Search This Blog

Thursday, April 4, 2013

Selecting GridView Row by clicking anywhere on the row


ASPX
<%@ page autoeventwireup="true" codefile="SelectRowWithoutSelectCommand.aspx.cs"
        inherits="GridView_SelectRowWithoutSelectCommand" language="C#" masterpagefile="~/MasterPages/Default.master"
        title="GridView: Select Row Without Select Command" %>
<asp:content id="Content1" runat="Server" contentplaceholderid="ContentPlaceHolder1">
        <asp:label id="Label1" runat="server" />
        <asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" datakeynames="ProductID,ProductName"
                datasourceid="SqlDataSource1" onselectedindexchanged="GridView1_SelectedIndexChanged"
                style="margin-top: 12px;">
                <columns>
                        <asp:boundfield datafield="ProductID" headertext="ProductID" readonly="True" sortexpression="ProductID" />
                        <asp:boundfield datafield="ProductName" headertext="ProductName" sortexpression="ProductName" />
                </columns>
        </asp:gridview>
        <asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="<%$ ConnectionStrings:NorthwindConnectionString %>"
                selectcommand="SELECT * FROM [Products]">
        </asp:sqldatasource>
</asp:content>
CODE-BEHIND
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class GridView_SelectRowWithoutSelectCommand : Page
{
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
                Label1.Text = String.Format("You selected product '{0}'.", GridView1.SelectedDataKey["ProductName"]);
        }

        protected override void Render(HtmlTextWriter writer)
        {
                const string onMouseOverStyle = "this.className='GridViewMouseOver';";
                const string onMouseOutStyle = "this.className='{0}';";
                
                foreach (GridViewRow gvr in GridView1.Rows)
                {
                        gvr.Attributes["onmouseover"] = onMouseOverStyle;
                        gvr.Attributes["onmouseout"] = String.Format(
                                onMouseOutStyle,
                                this.GetRowStyleCssClass(gvr.RowState));
                        gvr.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(
                                GridView1, 
                                String.Concat("Select$", gvr.RowIndex),
                                true);
                }
                
                base.Render(writer);
        }

        private string GetRowStyleCssClass(DataControlRowState state)
        {
                if ((state & DataControlRowState.Edit) > 0)
                {
                        return GridView1.EditRowStyle.CssClass;
                }
                else if ((state & DataControlRowState.Selected) > 0)
                {
                        return GridView1.SelectedRowStyle.CssClass;
                }
                else if ((state & DataControlRowState.Alternate) > 0)
                {
                        return GridView1.AlternatingRowStyle.CssClass;
                }
                else
                {
                        return GridView1.RowStyle.CssClass;
                }
        }
}
STYLESHEET
/* Element Styles */
body{
        background-color: #ffffff;
        color: #000000;
        font: normal normal normal 12px/20px Verdana, Geneva, Arial, Helvetica, sans-serif;
        margin: 10px;
}

pre{
        background: #FFFFB3;
        border: solid 1px blue;
        color: blue; 
        padding:10px; 
        margin: 10px; }
/* DetailsView Styles */
.DetailsView
{
        border: solid 1px #6699cc;
        margin-bottom: 12px;
}
.DetailsViewHeader
{
        background-color: #6699cc;
        color: #ffffff;
        font-size: 125%;
        font-weight: bold;
        text-align: center;
}
.DetailsViewFieldHeader
{
        font-weight: bold;
        text-align: right;
}
.DetailsViewCommandRow
{
        text-transform: lowercase;
}
/* FormView Styles */
.FormView
{
        border: solid 1px #6699cc;
        margin-bottom: 12px;
}       
/* GridView Styles */
.GridView
{
        border: solid 1px #6699cc;
        margin: 0px 0px 20px 0px;
}
.GridViewHeader
{
        background: #6699cc;
        color: #ffffff;
        font-size: 14px;
        font-weight: bold;
        text-align: left;
        vertical-align: bottom;
}
.GridViewRow
{
        background-color: #ffffff;
}
.GridViewAlternatingRow
{
        background-color: #ccffff;
}
.GridViewEditRow
{
        background-color: #f0e68c;
}
.GridViewMouseOver
{
        background-color: #f0e68c;
        cursor: hand;
}
.GridViewSelectedRow
{
        background-color: #f0e68c;
}
.GridViewFooter
{
        background-color: #ffffff;
}
.GridViewPager
{
        background-color: #6699cc;
        color: #ffffff;
        font-size: 14px;
        font-weight: bold;
}

Selecting GridView Row by clicking anywhere on the row

Introduction:
This post shows how to select a GridViewRow by clicking anywhere on the Row. Usually, We need to add a CommandField with Select Button or a ButtonField with Select CommandName to fire SelectedIndexChanged event. In this example, I am adding Onclick attribute for GridViewRow with javascript __doPostBack function to initiate a postback with Select Arguments.
Markup:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Selecting GridView Row</title>
    <style type="text/css">
        bodyhtml
        {
            font-family: Tahoma;
            font-size: small;
        }
        .Normal
        {
            background-color: #EFF3FB;
            cursor: hand;
        }
        .Normal:Hover.Alternate:Hover
        {
            background-color: #D1DDF1;
            cursor: hand;
        }
        .Alternate
        {
            background-color: White;
            cursor: hand;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView runat="server" ID="GridView1" DataKeyNames="ID" AutoGenerateColumns="False"
        CellPadding="4" Font-Names="Tahoma" Font-Size="Small" ForeColor="#333333" GridLines="None"
        OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound">
        <Columns>
            <asp:TemplateField HeaderText="Row">
                <ItemTemplate>
                    <%# Container.DataItemIndex+1 %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="FirstName" HeaderText="First Name" />
            <asp:BoundField DataField="LastName" HeaderText="Last Name" />
            <asp:CommandField ShowSelectButton="true" ButtonType="Link" Visible="false" SelectText="Enroll" />
        </Columns>
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    </asp:GridView>
    <br />
    <asp:Label Text="" ID="lblSelectedRow" runat="server" />
    </form>
</body>
</html>

Description:
We need to add onclick attribute for GridViewRow in RowDataBound and we need to add that attribute only for DataRows.

CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridView1.DataSource = Enumerable.Range(1, 10).Select(a => new
        {
            ID = a,
            FirstName = String.Format("First Name {0}", a),
            LastName = String.Format("Last Name {0}", a)
        });
        GridView1.DataBind();
    }
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    lblSelectedRow.Text = String.Format("You selected row {0} with {1} {2}",
                                            GridView1.SelectedIndex + 1,
                                            GridView1.SelectedRow.Cells[0].Text,
                                            GridView1.SelectedRow.Cells[1].Text);
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //add css to GridViewrow based on rowState
        e.Row.CssClass = e.Row.RowState.ToString();
        //Add onclick attribute to select row.
        e.Row.Attributes.Add("onclick"String.Format("javascript:__doPostBack('GridView1','Select${0}')", e.Row.RowIndex));
    }
}

http://forums.asp.net/t/1666327.aspx/1
http://dotnetspeaks.net/post/Selecting-GridView-Row-by-clicking-anywhere-on-the-row.aspx

1 comment: