How to develop a row-clickable GridVIew control?

This post shows you how to develop a row Clickable GridView, clicking the row (e.g entire row, not specific column) in the control causes a postback and throws RowClicked event. This can be used to customize selections a user can make with the control.I added CSS class properties to the grid, to allow a different style applied to a row if hovered over. [Code for the control]
using System;
using System.ComponentModel;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomGridView
{
/// <summary>
/// Summary description for ClickableGridView
/// </summary>
public class ClickableGridView : GridView
{
    public string RowCssClass
    {
        get
        {
            string rowClass = (string)ViewState["rowClass"];
            if (!string.IsNullOrEmpty(rowClass))
                return rowClass;
            else
                return string.Empty;
        }
        set
        {
            ViewState["rowClass"] = value;
        }
    }

    public string HoverRowCssClass
    {
        get
        {
            string hoverRowClass = (string)ViewState["hoverRowClass"];
            if (!string.IsNullOrEmpty(hoverRowClass))
                return hoverRowClass;
            else
                return string.Empty;
        }
        set
        {
            ViewState["hoverRowClass"] = value;
        }
    }

    private static readonly object RowClickedEventKey = new object();

    public event GridViewRowClicked RowClicked;
    protected virtual void OnRowClicked(GridViewRowClickedEventArgs e)
    {
        if (RowClicked != null)
            RowClicked(this, e);
    }

    protected override void RaisePostBackEvent(string eventArgument)
    {
        if (eventArgument.StartsWith("rc"))
        {
            int index = Int32.Parse(eventArgument.Substring(2));
            GridViewRowClickedEventArgs args = new GridViewRowClickedEventArgs(Rows[index]);
            OnRowClicked(args);
        }
        else
            base.RaisePostBackEvent(eventArgument);
    }

    protected override void PrepareControlHierarchy()
    {
        base.PrepareControlHierarchy();

        for (int i = 0; i < Rows.Count; i++)
        {
            string argsData = "rc" + Rows[i].RowIndex.ToString();
            Rows[i].Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(this, argsData));

            if (RowCssClass != string.Empty)
                Rows[i].Attributes.Add("onmouseout", "this.className='" + RowCssClass + "';");

            if (HoverRowCssClass != string.Empty)
                Rows[i].Attributes.Add("onmouseover", "this.className='" + HoverRowCssClass + "';");
        }
    }
}

public class GridViewRowClickedEventArgs : EventArgs
{
    private GridViewRow _row;

    public GridViewRowClickedEventArgs(GridViewRow aRow)
        : base()
    {
        _row = aRow;
    }

    public GridViewRow Row
    {
        get
        { return _row; }
    }
}

public delegate void GridViewRowClicked(object sender, GridViewRowClickedEventArgs args);
}
[Usage example]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RowClickableGrid.aspx.cs"
 Inherits="Meta" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register Namespace="CustomGridView" TagPrefix="sc" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Untitled Page</title>
 <style type="text/css">

 .hover{color:red}
 </style>
</head>
<body>
 <form id="form1" runat="server">
     <div>
         <sc:ClickableGridView ID="GridView1" runat="Server" HoverRowCssClass="hover" OnRowClicked="GridView1_RowClicked">
         </sc:ClickableGridView>
     </div>
 </form>
</body>
</html>
[code-behind]


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Meta : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
       {

           BindGridViewView();
       }

   }
   private void BindGridViewView()
   {
       if (Session["strTemp"] != null)
       {

           GridView1.DataSource = Session["strTemp"] as DataTable;
           GridView1.DataBind();

       }
       else
       {
           GridView1.DataSource = GetCustomMadeDataTable();
           GridView1.DataBind();
       }
   }
   public DataTable GetCustomMadeDataTable()
   {
       //Create a new DataTable object
       System.Data.DataTable objDataTable = new System.Data.DataTable();
       //Create three columns with string as their type
       objDataTable.Columns.Add("ISBN", typeof(string));
       objDataTable.Columns.Add("Title", typeof(string));
       objDataTable.Columns.Add("Publisher", typeof(string));
       objDataTable.Columns.Add("Year", typeof(string));
       DataColumn[] dcPk = new DataColumn[1];
       dcPk[0] = objDataTable.Columns["ISBN"];
       objDataTable.PrimaryKey = dcPk;
       objDataTable.Columns["ISBN"].AutoIncrement = true;
       objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
       //Adding some data in the rows of this DataTable
       DataRow dr;
       for (int i = 1; i <= 10; i++)
       {
           dr = objDataTable.NewRow();
           dr[1] = "Title" + i.ToString();
           dr[2] = "Publisher" + i.ToString();
           dr[3] = "200" + i.ToString();
           objDataTable.Rows.Add(dr);
       }
       Session["strTemp"] = objDataTable;
       return objDataTable;
   }
   protected void GridView1_RowClicked(object sender, CustomGridView.GridViewRowClickedEventArgs args)
   {
       Response.Write("Index of the clicked row was: " + args.Row.RowIndex.ToString());
   }
}

1 comment:

  1. How do i change selected row color.....in GridView1_RowClicked from above code

    ReplyDelete