Search All Articles Submit your Website or Blog to A New Internet Library
Sunday, February 15, 2009
Making GridView Rows or Individual Cells Clickable and Selectable.
Introduction:
In some scenarios we need to make GridView rows clickable and also in some cases we may need to make each cell of the GridView clickable like while developing reports.
We need to attach some event to each GridView row or each GridView cell to get the rowindex and cellindex (ColumnIndex) on which the user has clicked or double clicked.
This article shows you how to add attributes like click or double click GridView row or GridView individual cell and get the details of selected Row or Cell.
Description:
Making GridView with Selectable Rows:

- First create a new Website application, attach any database or add connection string to the existing database in the web.config file.
- Add gridview along with DataSource control (
SqlDataSourcecontrol)on to the page. Configure DataSource control to get records from some table. - Assign
DataSourceIdof the GridView with the ID of the SqlDataSource control. - Add
ButtonFieldto the GridView columns.
<asp:ButtonField CommandName="Select" Visible="false" />
RowDatabound event is fired while binding each row to the GridView. Now we need to handle GridView OnRowDataBound event to modify each row as it is bound, where we can add attributes to each GridView row to handle Onclick or OnDouble click event by adding client script which is used by the SingleClick button for postback and assign it to the entire row.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get reference to button field in the gridview.
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" + e.Row.RowIndex);
e.Row.Style["cursor"] = "hand";
e.Row.Attributes["onclick"] = _jsSingle;
}
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get reference to button field in the gridview.
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" + e.Row.RowIndex);
e.Row.Style["cursor"] = "hand";
e.Row.Attributes["ondblclick"] = _jsSingle;
}
}
}
OnSelectedIndexChanged event.GridView’s OnSelectedIndexChanged event to get the selected row as below.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectedRow = GridView1.SelectedRow;
lblSelectedRow.Text = GridView1.SelectedIndex.ToString();
lblName.Text = selectedRow.Cells[2].Text;
lblEmpId.Text = selectedRow.Cells[3].Text;
}
Invalid postback or callback argument (Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.) error.RegisterForEventValidation method in order to register the postback or callback data for validation.
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
ClientScript.RegisterForEventValidation(((LinkButton)row.Cells[0].Controls[0]).UniqueID, "Select$" + row.RowIndex);
}
}
base.Render(writer);
}

Making each GridView individual cells Clickable and Selectable:

- First create a new Website application, attach any database or add connection string to the existing database in the web.config file.
- Add gridview along with DataSource control (SqlDataSource control) on to the page. Configure DataSource control to get records from some table.
- Assign DataSourceId of the GridView with the ID of the SqlDataSource control.
- Add ButtonField with some
Command Namesay“ColumnClick”to the GridView columns.
<asp:ButtonField CommandName="ColumnClick" Visible="false" />
RowDatabound event is fired while binding each row to the GridView. Now we need to handle GridView OnRowDataBound event to modify each cell in each GridView row as it is bound, where we can add attributes to each GridView cell to handle Onclick or OnDouble click event by adding client script which is used by the SingleClick button for postback and assign it to each cell.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
// Add events to each editable cell
for (int columnIndex = 0; columnIndex < e.Row.Cells.Count; columnIndex++)
{
// Add the column index as the event argument parameter
string js = _jsSingle.Insert(_jsSingle.Length - 2, columnIndex.ToString());
// Add this javascript to the onclick Attribute of the cell
e.Row.Cells[columnIndex].Attributes["onclick"] = js;
// Add a cursor style to the cells
e.Row.Cells[columnIndex].Attributes["style"] += "cursor:pointer;cursor:hand;";
}
}
}
}
OnRowCommand event.GridView’s OnRowCommand event to get the selected cell details as below. Within the RowCommand event, the command argument and the event argument are retrieved. This gives us the row and column index of the selected cell.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "ColumnClick")
{
foreach (GridViewRow r in GridView1.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
for (int columnIndex = 0; columnIndex < r.Cells.Count; columnIndex++)
{
r.Cells[columnIndex].Attributes["style"] += "background-color:White;";
}
}
}
int selectedRowIndex = Convert.ToInt32(e.CommandArgument.ToString());
int selectedColumnIndex = Convert.ToInt32(Request.Form["__EVENTARGUMENT"].ToString());
GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Attributes["style"] += "background-color:Red;";
lblSelectedColumn.Text = selectedColumnIndex.ToString();
lblSelectedRow.Text = selectedRowIndex.ToString();
lblSelectedColumnTitle.Text = GridView1.Columns[selectedColumnIndex].HeaderText;
lblSelectedColumnValue.Text = GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Text;
}
}
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow r in GridView1.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
for (int columnIndex = 0; columnIndex < r.Cells.Count; columnIndex++)
{
Page.ClientScript.RegisterForEventValidation(r.UniqueID + "$ctl00", columnIndex.ToString());
}
}
}
base.Render(writer);
}

Download the Sample Code here.
Subscribe to:
Post Comments (Atom)
Also Read other Top Articles
- JSON Serialization in VS 2008
- Implementing Forms Authentication in Silverlight Application.
- Making GridView Rows or Individual Cells Clickable and Selectable.
- Enabling browser back button for GridView Paging and Sorting in Ajax 1.1 and 3.5 (using Visual Studio 2005/ Visual studio 2008)
- How to pass values from User Control to Page or calling Page methods from User Control.
- What is WCF?
- New features in C# 4.0
- C# to VB.NET and VB.NET to C# online free converter tools.


37 comments:
Very nice one....
A real good article. I will try it and will send you my feedback. Thanks.
Bikram.
That's the real thing.
Good work.
good job thanks
its nice
pretty useful article. good work author :)
Nice one!
Thanks for this great tutorial, I have tried it in my own GridView, works like a charm! :)
I am having some issues with this one...I am getting error message "Unable to cast object of type 'System.Web.UI.WebControls.Label' to type 'System.Web.UI.WebControls.LinkButton'." when running this code. Any suggestions?
Hi Ashley,
Make sure that you have added ButtonField as first column in GridView.
Hi,
How can i use this code to be able to select more than one cell at the same time?
Is there a VB.net version?
You can convert the code into VB.NET use tools like mentioned here to convert C# to VB.NET.
http://interviews.dotnetthread.com/2008/11/toolsc-to-vbnet-and-vbnet-to-c-online.html
thanks mama
To Good Article...It saved my life... Thanks man
Is it possible to do that with several dynamic gridviews ?
are you able to put this into a function so it can be perfomed on a button click?
Very nicely done, this helped me out. A lot better done than a lot of other samples out there.
Very useful.Many Thanks
Regards
Feroz
Very interesting....
That helped me a ton. Thanks for posting!!!
Thank you. Your article helped me tremendously. ~ Ken
Good Work
Its Working ... Thank you very much.. and Good Luck!
Protected Sub gdEmp_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gdEmp.RowCommand
If e.CommandName = "Select" Then
'Do select
Dim rowIndex As Integer = Integer.Parse(e.CommandArgument.ToString())
Dim lbl As Label = DirectCast(gdEmp.Rows(rowIndex).Cells(1).FindControl("Label1"), Label)
Dim connection = sqlcon()
Dim command As New SqlCommand("select * employee where empid=';", connection)
' For Each row As GridViewRow In gdEmp.Rows
Dim intId As Integer = gdEmp.SelectedIndex()
' Next
connection.Open()
command.ExecuteNonQuery()
connection.Close()
' ElseIf e.CommandName = "Deleterow" Then
'Do Delete
'Dim command As New SqlCommand("delete from employee;", connection)
End If
End Sub
any one help me in this how can i select the particular row or data of that row......
Im having a problem, i want to have MORE THAN ONE DATAGRID controls but the events above to be handled from the same handlers. i`ve made this change:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView x = new GridView();
x = (GridView)sender;
foreach (GridViewRow r in x.Rows) ......
but when i select a cell in the second grid the cell in the first is deselected. Please help
Great Article! Helped me a lot!
I am working on this and i am a novice user or developer. I doubt is, your instructions say to ass a button field. Were do i add this button field in my page? some where around the grid??
Thank You
I am working on this and i am a novice user or developer. My doubt is, your instructions say to add a button field. Were do i add this button field in my page? some where around the grid??
Thank You
I am facing these errors. can any one please help me.
///
The name 'lblSelectedColumn' does not exist in the current context
The name 'lblSelectedRow' does not exist in the current context
The name 'lblSelectedColumnTitle' does not exist in the current context
The name 'lblSelectedColumnValue' does not exist in the current context
///
Thank you
Download the source code ...
Hi Anil,
Sorry to bother you but...
I've added your code to my project but the rows still aren't clickable.
I can watch the overridden 'render' function run, but the 'RowDataBound' code never runs. It's as if the event never fires.
I'm using an AccessDataSource instead of an SQLDataSource - Do you think this could make any difference to the events that get fired as the control is built for the page?
Thanks,
Paul.
Makes perfect sense works good.You should face with a problem about linkbutton casting.you should check it from your designview section
hi is it possible to write click and double click events at the same time in rowdatabound.
i.e will click and double click events work simultaneously
Hi
Thanks for the article. Its very nice and helpful for me.
wonderful article ever...
this is what i've been dreaming of since i started learning ASP.NET :P
Post a Comment
Post your comments/questions/feedback for this Article.