Monday, March 31, 2008

Gridview + Click anywhere on row to Edit + vb.net

If you want to be able to click anywhere on a gridview row and put it into edit mode then you can use this piece of code on the RowDataBound event:



e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(DirectCast(sender, System.Web.UI.Control), "Select$" + e.Row.RowIndex.ToString()))


Then on the RowCommand Event:


If e.CommandName = "Select" Then
GridView1.EditIndex = e.CommandArgument
End If


You can download a sample Visual Studio 2005 solution here

Update
---------------------------
Getting this error message?

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.

If you don't want to set enable event validation to false then you can try the following:

Protected Overloads Overrides Sub Render(ByVal writer As HtmlTextWriter)
For i As Integer = 0 To Me.gv1.Rows.Count - 1
Page.ClientScript.RegisterForEventValidation(Me.gv1.UniqueID, "Select$" & i)
Next
MyBase.Render(writer)
End Sub

4 comments:

Lourdes said...

Your posting was very helpful! I'm a newbie and this so far is the easiest method that I have found.

DayDreamer said...

Really neat skillz .....but I was not able to download the file...could u provide a working link for download....would be helpful..

aApe said...

That sweet. Just the kind of thing I was looking for. It chokes when your gridview is inside an AJAX updatepanel, but I'm sure I figure a work around.

If I get it, I'll put in pastebin, and post a link.

Thanks dude.

aApe said...

I rescind my above statement re it choking in update panel. It was my nubitude that was causing it to choke. It works just fine.

THANKS!