Tuesday, April 21, 2009

Using button field to get datakey

Scenario:

Consider we have a data grid view which show a list of books from database and you want a link button which will edit the same grid view entry but in a separate page and on separate form with the help of the primary key which you may want to send to another page using query string or else.
So the task is to get the primary key of the row on which the link button is pressed.

Solutions:

it can slove by three way
1-by using command argument
2- By using hidden field
3-by using datakeys

First of all doing it convert button field into template

Approach (1)

1- By using Command Argument.





‘ runat=”server”>Edit





Then we write simple code on onRowCommand Event

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand

If e.CommandName.ToLower() = “edit” Then

Dim Key As String = e.CommandArgument ’Getting id Value

Response.Redirect(makeeditForm.aspx?id=” + Key) ‘redirecting

End If

End Sub
-----------------------------------------------------------------------------------
Approach (2)

2-By using hidden field



‘ />
Edit





Then we write simple code on onRowCommand Event

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand

If e.CommandName.ToLower() = “edit” Then

Dim link As LinkButton = CType(e.CommandSource, LinkButton) ‘getting clicked button

Dim Key As String = CType(link.Parent.FindControl(”hidden1”), HiddenField).Value ‘getting id Value

Response.Redirect(makeeditForm.aspx?id=” + Key) ‘redirecting

End If

End Sub
---------------------------------------------------------------------------------------
Approach(3)

3-by using datakeys





Edit





Then we write simple code on onRowCommand Event

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand

If e.CommandName.ToLower() = “edit” Then

Dim link As LinkButton = CType(e.CommandSource, LinkButton) ‘getting clicked button

Dim Row As GridViewRow = link.BindingContainer ‘Getting current row to get index

Dim Key As String = GridView1.DataKeys(Row.RowIndex)(0).ToString()

Response.Redirect(makeeditForm.aspx?id=” + Key) ‘redirecting

End If

End Sub

No comments:

Post a Comment