user4370502
user4370502

Reputation:

Getting text from labels inside gridview cells (VB)

VB

I've got a gridview in which I need to use template columns, therefore instead of being able to retrieve text straight from the cell, it's inside of a label. All the labels have different ids as well so I would like to programmatically retrieve the label inside a cell then look at the text inside the label.

This is what I have got at the moment, however it never manages to return the text and instead returns the empty string ("").

Public Function ReturnLabelText(ByVal c As TableCell) As String
    For Each lb In c.Controls
        If lb.[GetType]() = GetType(Label) Then
            Return CType(lb, Label).Text()
        End If
    Next
    Return ""
End Function

The function is called on this line:

doc.ReplaceText("@" + gridView.HeaderRow.Cells(i).Text.ToLower, ReturnLabelText(row.Cells(i)).Replace(" ", "").Replace(vbCr, ""))

Upvotes: 1

Views: 3862

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

You have to use GridViewRow.FindControl("ControlID") to get the reference of the Label.

So for example, if you want to loop loop all rows:

For Each row As GridViewRow In Me.GridView1.Rows
    Dim label = DirectCast(row.FindControl("LabelID"), Label)
    Dim text As String = label.Text
    ' ... '
Next

But if you want to set it's text on databinding i'd use the GridView.RowDataBound event instead:

Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
    Select Case e.Row.RowType
        Case DataControlRowType.DataRow
             Dim label = DirectCast(e.Row.FindControl("LabelID"), Label)
             Dim text As String = label.Text
    ' ... '
    End Select
End Sub

You can even get the DataSource of each row via e.Row.DataItem to access all fields.


If you have a TableCell and you want to get all labels in it you could also use OfType:

Dim firstLabel = c.Controls.OfType(Of Label)().FirstOrDefault()
If firstLabel  IsNot Nothing Then Return firstLabel.Text
Return Nothing

Upvotes: 2

Related Questions