MyHeadHurts
MyHeadHurts

Reputation: 1562

button in gridview to take a grid control value, and place it in a label

So basically what i am trying to do is, take the id value of the row that is clicked , and place it in a label outside of the gridview, however, when i do this the label come up with no text.

I think my problem is that x is not being set to the exact row that is being clicked but i am not sure.

 Dim x As String
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim id As Label = CType(e.Row.FindControl("id"), Label)
            Dim button As Button = CType(e.Row.FindControl("button1"), Button)


            x = id.Text

            ' Dim link As HyperLink = CType(e.Row.FindControl("HyperLink1"), HyperLink)
            ' link.NavigateUrl = "Default2.aspx?id=" + id.Text

        End If
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Label2.Text = x

    End Sub

Upvotes: 0

Views: 1931

Answers (2)

MyHeadHurts
MyHeadHurts

Reputation: 1562

Using the gridview1_rowcommand worked

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
            If (e.CommandName = "Action") Then
                ' Retrieve the row index stored in the CommandArgument property.
                Dim index As Integer = Convert.ToInt32(e.CommandArgument)

                ' Retrieve the row that contains the button 
                ' from the Rows collection.
                Dim row As GridViewRow = GridView1.Rows(index)
                Dim id As Label = CType(GridView1.Rows(index).FindControl("id"), Label)
                x = id.Text
                Label2.Text = x
            End If

Upvotes: 0

Bala R
Bala R

Reputation: 109027

Skip the RowDataBound event and try this, (sorry by VB is a little bit rough)

   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

         Dim button As Button = CType(sender, Button)
         Dim label As Label = CType(button.Parent.FindControl("id"), Label)

        Label2.Text = label.Text

    End Sub

Upvotes: 1

Related Questions