Introduction
I was playing with the GridView
control and suddenly the question came up in my mind that how could I select a GridView
control row while clicking on any area of the GridView
control rather than depending on the Select button of the GridView
control. Then I Googled for some time but could not find the exact solution. A lot of solutions were available for the selection of a row but I could not find a solution which when I clicked on the GridView
, updates the DetailView
automatically by grabbing the SelectionIndexChanged
event. Following are the results of my search for a solution. Please let me know if this can be done by any other way.
Using the code
First, you need to bind the RowDataBound
event to the GridView
. Then in that event, write the following code.
In this code, the first line checks if the ItemIndex
passed is proper. Then it adds the script for mouse over for the cursor to change to the Hand cursor. In the next line, it adds the postback client event by calling the GetPostBackClientEvent
function with two arguments. The first argument contains the GridView
object and the second argument contains a string that contains the event and the parameter. Like, if you want to call the SelectedIndexChange
event, you need to pass the 'Select' as the event and the RowIndex
to select as the parameter. You need to combine the text using $. So if you give 'Select$4' as the second argument, it calls the SelectedIndexChanged
event for fourth row as SelectedRow
.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex == -1)
return;
e.Row.Attributes.Add("onMouseOver",
"this.style.cursor='hand';");
e.Row.Attributes.Add("onclick",
this.GetPostBackClientEvent(GridView1,
"Select$" + e.Row.RowIndex.ToString()));
}
Similarly, the following are the other parameters you can use for calling other events:
- "Sort${ColumnName}" - Here {ColumnName} can be the
DataField
of the column you want to sort.
- "Page${PageNumber}" - Here {PageNumber} is the page number you want to select.
- "Delete${RowNumber}"- Here {RowNumber} is the row number you want to delete.
- "Edit${RowNumber}" - Here {RowNumber} is the row number you want to edit.
So you can write any postback client side event by passing the GridView
name and the above listed parameter as said. So suppose if I want to change the page number by a control's OnClick
event, I simple add a postback reference to the OnClick
event of that control like so: e.Row.Attributes.Add("onclick", this.GetPostBackClientEvent({{GRIDVIEWOBJECT} ,"Delete$" + e.Row.RowIndex.ToString()));
. The above code simply writes a postback client event's JavaScript on the "OnClick
" event of that control. When we click on the control, it calls the delete functionality of the DataGrid
.