Click here to Skip to main content
Click here to Skip to main content

Steps to Write GridView PostBack Events

By , 6 Jan 2006
 

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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Manish Pansiniya
Founder IntelliPro Solutions Pvt. Ltd.
India India
Member
Organisation (No members)

A 8 or something in .NET, living in Ahmedabad, India owned IntelliPro Solutions Pvt. Ltd..
 
Currently working on .NET technologies, MVC and Silverlight.
 
My little blog is for helping community with the solution for problems or helping them to understand new technology. You can reach to my blog at http://maniish.wordpress.com.
 
To contact me, post comment here or email me at manish AT iprospl.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionPageMethods are neater solutionmemberManjit Dosanjh11 Aug '12 - 13:21 
Using pagemethods you can get a neater solution with no need for a postback. It's what AJAX was created for!! Squiffy!
 
Creating and consuming page methods
"If the facts don't fit the theory, change the facts."

GeneralMy vote of 5memberAsween26 May '11 - 6:03 
Perfect solution!
GeneralProblem with dynamic gridviewmemberMember 786028326 May '11 - 4:59 
Hi,
I saw your post.it is very nice and i tried that code but i had a problem while running that code.I want to put sorting event for dynamic gridview. I have nearly 10 dynamic gridviews in my page.I added the above code.The cursor style is changed to hand but while clicking on any gridview all the page content is lost.why? what is the problem? pls give me the solution.
GeneralRe: Problem with dynamic gridviewgroupManish Pansiniya26 May '11 - 8:20 
Hi, I think you are loading your dynamic gridview in !IsPostBack...so whenever there is postback, all content is lost. Let me know how you are loading your gridview.
---------------------
Manish Pansiniya

Generalredirectionmemberxiaota21 Oct '07 - 2:08 
Hi,
After clicking, is that possible to redirect to another web page? (such as an HyperLinkField & to recover the Id of the selected row with the Request.QueryString)
 
best regards
 
bruno
Questionhow can i fire the ItemCommand from here?memberluzer29 Jun '07 - 9:26 
this it supposed to fire the _ItemCommand event, but it doesnt.
 
any ideas?

ImageButton imbSave = (ImageButton)e.Item.FindControl("imbSave");
if (imbSave != null)
{

imbSave.Attributes.Add("onclick", "javascript:" +
"document.getElementById('" + imbSave.ClientID + "')" + ".disabled=true;" +
Page.ClientScript.GetPostBackEventReference(AccountCategoryGrid, "Select$" + AccountCategoryGrid.EditItemIndex));
 
}

GeneralDisabling "onclick" event when the edit button is clickedmembernicosiam6 Apr '07 - 6:28 
Hello, I would like to disable the onclick event from occuring on a row after the user clicks the edit button and is trying to edit a boundcolumn. I was able to disable the onclick event from occuring when the user clicked the edit button by adding an additional onclick attribute to the cell containing the edit button: event.cancelBubble=true;. However, I tried using the OnRowEditing command and adding this same onclick attribute to the row being edited but have been unsuccessful thus far. Any ideas?
 
Thanks,
Mike.
GeneralRe: Disabling "onclick" event when the edit button is clickedmemberManish Pansiniya6 Apr '07 - 7:14 
can't you make one flag for editing and put that check in rowdatabound event whether to add onclick code or not. Pls tell me if i understood nething wrong.

 
---------------------
Manish Pansiniya

GeneralRe: Disabling "onclick" event when the edit button is clickedmembernicosiam9 Apr '07 - 8:59 
when i click the edit button, rowdatabound event is not executed; rowediting is executed. once you are in edit mode, the onclick event will still occur due to the underlying onclick event for that cell. so i need to disable the the onclick event from occuring when rowediting is occuring.
GeneralRe: Disabling "onclick" event when the edit button is clickedmemberManish Pansiniya10 Apr '07 - 1:16 
Use the following code. Let me know if it cant be understood.
 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex == -1)
return;
 
if (GridView1.EditIndex < 0)
{
e.Row.Attributes.Add("onMouseOver",
"this.style.cursor='hand';");
e.Row.Attributes.Add("onclick",
this.GetPostBackClientEvent(GridView1,
"Select$" + e.Row.RowIndex.ToString()));
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = Supplier.FetchAll();
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.DataSource = Supplier.FetchAll();
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.DataSource = Supplier.FetchAll();
GridView1.DataBind();
}
 
---------------------
.NET Blogs

GeneralRe: Disabling "onclick" event when the edit button is clickedmembernicosiam10 Apr '07 - 6:37 
Excellent. I didn't know it was that easy to check the EditIndex. Works perfectly now. Thanks. Big Grin | :-D
QuestionObject Null in Edit Mode of Grid Viewmemberitsbijusamuel29 Mar '07 - 21:23 
Hi,
Some one please help me to this in a Grid View, when in edit mode.
I'm trying to use a calendar(javascript) in my edit item template.
But when the edit event is fired i'm getting the object as null.
Kindly help.
My code is shown below.
 

<asp:TextBox ID="TextBox10" runat="server" Text='<%# Bind("NoOfCriticalRolesWith2ICInPlaceDate") %>'>
<IMG style="WIDTH: 23px; HEIGHT: 20px" height="20" alt="Click Here to Pick up the date"
src="images/cal.gif" width="23" border="0">

<SCRIPT language="JavaScript">
var cal1 = new calendar1(document.getElementById('teamEntry_grdTeamHeader_ctl02_TextBox10'));
cal1.year_scroll = true;
cal1.time_comp = false;


</SCRIPT>

AnswerRe: Object Null in Edit Mode of Grid ViewmemberManish Pansiniya30 Mar '07 - 2:44 
Hello,
 
See, basically, i didn't get exactly wat is ur problem. But check the following thing.
- R u getting calendar1 object outside of the grid. Means is the script file included.
- Now, check whether u geting exactly same textbox id as shown in the getElementById function.
 
Please let me know in detail with above checks
 
---------------------
Manish Pansiniya

Generalevent for clicking on grid view rowsmemberNigam SAMir4 Feb '07 - 17:56 
Hi! i want on clicking any row of grid view, the form should post back & on server side a specific method get executed. just like on clicking on a button, form is post back & button's click method is called on server side. please help me
 
Thanks & Regards,
SAMir Nigam,
Software Developer,
STPL, Lucknow, India.

GeneralRe: event for clicking on grid view rowsmemberManish Pansiniya4 Feb '07 - 19:22 
In this functionality, if you implement the functionality to select the record then selectedindexchanged of grid is fired and i think that is your solution.
 
Please let me know if it helps.
 
Thank you,
 
---------------------
www.pansiniya.com/blog

QuestionGreat - So simple, but Firefox ...memberericVV19 Jan '07 - 23:02 
This is a very simple and usefull method, but with firefox the hand do not appear.
 
Do you have any idea or solution ?

AnswerRe: Great - So simple, but Firefox ...memberManish Pansiniya19 Jan '07 - 23:49 
i believe there is different setting for firefox. That is cursor=pointer. Please search in google and you can find it.
 
---------------------
www.pansiniya.com/blog

GeneralRe: Great - So simple, but Firefox ...membersaille19 Apr '07 - 16:37 
Yes, cursor=pointer seems to display the hand for IE (IE7) as well as in FireFox, so it would seem to be a worthwhile improvement.
 

GeneralRe: Great - So simple, but Firefox ...memberManish Pansiniya20 Apr '07 - 17:56 
If it is such then then great. But still we need to support IE5 and IE6 as their userbase is still considerable. Right. Thanks for info.
 
---------------------
Manish Pansiniya

GeneralExcellent solutionmemberPujari12 Dec '06 - 0:04 
This is a simple and best solution I have ever found for this issue. great contribution.
GeneralRe: Excellent solutionmemberManish Pansiniya12 Dec '06 - 3:54 
I have just posted one great control. When it is available will let you know on this thread or search it on code project after 10 to 15 days. That is ZatakTextBox. I am sure you like it.
http://maniish.wordpress.com[^]
 
Never Give Up
Generalusing this method with dynamically created gridviewmemberwendigt1 Nov '06 - 3:54 
I have been using this method to select a gridview row with a gridview that was added to my page at design time. I had to change to adding the gridview control dynamically at runtime and adding it to a placeholder control. The control is built and bound before page_load event fires, but is added to the page upon page_load. Now, when running this code, I get a "object reference not set to an instace of an object" error. I changed my code to this:
 
oCell.Attributes.Add("onClick", Page.GetPostBackClientEvent(sender, "Select$" & e.Row.RowIndex.ToString()))
 
during debug, i've checked that 'sender' is my gridview object. any ideas?

GeneralRe: using this method with dynamically created gridviewmemberwendigt1 Nov '06 - 4:10 
I figured it out. I don't have reference to Page object at this point....moved to another event. Thanks.
GeneralChecking on validation Problemmemberdpmvpa14 Sep '06 - 6:54 
I recently sent the error msg and was interested to know if you had a chance to check to see the problem
Dean
GeneralValidation problemsmemberdpmvpa13 Sep '06 - 2:14 
Here, is the error I am getting:
I tried to set enableEventValidation to false but I still get an error
 
Dean McIntire
Thanks for your help!!
 
Server Error in '/VE2007sced2' Application.
--------------------------------------------------------------------------------
 
Invalid postback or callback argument. Event validation is enabled using 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.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
 
Exception Details: System.ArgumentException: Invalid postback or callback argument. Event validation is enabled using 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.
 
Source Error:
 
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
 
Stack Trace:
 

[ArgumentException: Invalid postback or callback argument. Event validation is enabled using 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.]
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +358
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +29
System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +172
 


 
dpmvpa@comcast.net
Dean McIntire

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 7 Jan 2006
Article Copyright 2006 by Manish Pansiniya
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid