0

I am creating a textbox and button dynamically like this inside a FlowLayoutPanel:

        Dim txtRating As New TextBox
        txtRating.Name = "buildingRating_" + intCount.ToString

        Dim btnAddRating As New Button
        btnAddRating.Name = "addRating_" + intCount.ToString

And then I create an event handler for the button:

    AddHandler btnAddRating.Click, AddressOf HandleAddRatingButtonClick

Each textbox and button will be associated with each other with the intCount value, so it would look like this:

buildingRating_1   addRating_1
buildingRating_2   addRating_2
buildingRating_3   addRating_3
etc....

I need to get the value of the textbox that is in associated with the button.

For example, if the user clicks the button named addRating_1, the text value of buildingRating_1 will be saved a database...

Is there a way to get that association or pass intCount into the btnAddRating.Click event that I am creating?

Thanks!

3
  • 2
    NET user events are fixed so you cant pass anything to it. You could find the associated text control either by a) looking into the adjacent column, b) parsing the sender name to create the text control name (except for addRating_4 c) create a user control that has both on it and encapsulates the dual nature c) create a look up list to get once from the other Commented Nov 13, 2017 at 19:23
  • 1
    Why not use a lambda for the handler? Commented Nov 13, 2017 at 19:29
  • @djv typo (fixed) Commented Nov 13, 2017 at 19:32

1 Answer 1

2

Extract the index from the name of the button, and use it to recreate the name of the textbox. Then find the textbox on the form.

Private Sub HandleAddRatingButtonClick(sender As Object, e As EventArgs)
    Dim button = DirectCast(sender, Button)
    Dim index = button.Name.Split("_"c).Last()
    Dim textboxname = "buildingRating_" & index
    Dim textbox = Me.Controls.OfType(Of TextBox).Single(Function(tb) tb.Name = textboxname)
    Dim text = textbox.Text ' this is the text
End Sub

If the textbox is in a container (panel, groupbox, etc.) then instead of Me.Controls... do Container.Controls...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.