Get DataKey on RowDataBound

M

MasterChief

I am trying to add an attribute to a gridview row so when you click on
it, it will pop up an alert saying the current datakey for that row.
How is it possible to get a datakey when using the rowdatabound I want
to do something like

If (e.Row.RowType = DataControlRowType.DataRow) Then
e.row.attribute.add("onClick", "alert('" + KeyID + "')'")
End If

but I don't know how to get the KeyID? Any help would be appreciated.
 
T

tdavisjr

MasterChief said:
I am trying to add an attribute to a gridview row so when you click on
it, it will pop up an alert saying the current datakey for that row.
How is it possible to get a datakey when using the rowdatabound I want
to do something like

If (e.Row.RowType = DataControlRowType.DataRow) Then
e.row.attribute.add("onClick", "alert('" + KeyID + "')'")
End If

but I don't know how to get the KeyID? Any help would be appreciated.

You need to hande the RowCommand Event.

Then retreive the datakey

DataKey key = GridView1.DataKeys[e.CommandArgument]

Then the the key should have a Value property which is the datakey.
Now, I'm doing this totally from memory; but this should point you in
the right diretion.
 
T

tdavisjr

Oops. The index to the DataKeys is probably an integer so please cast
c.CommandArgument appriately.
 
M

MasterChief

I can get the DataKey using the RowCommand Event but I want to be able
to put the OnClick attribute into the Row and have it alert the KeyID.
When I try to get the value of KeyID that I got in RowCommand it comes
back with a null value. The only way I can find to add an attribute to
a row is during the RowDataBound Event.

Public Class _MasterTestBed
Inherits System.Web.UI.Page
Dim KeyID As String
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e
As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles
GridView1.RowCommand
KeyID = GridView1.DataKeys(e.CommandArgument).Value.ToString
End Sub

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal
e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles
GridView1.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
e.Row.Attributes.Add("onMouseOver",
"this.style.backgroundColor='lightgrey'")
e.Row.Attributes.Add("onMouseOut",
"this.style.backgroundColor='Transparent'")
e.Row.Attributes.Add("onClick", "alert('" + KeyID + "')'")
End If
End Sub
End Class
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top