How to call a dynamically created label from its associated dynamically created button's click in vb.net

StackOverflow https://stackoverflow.com/questions/18804443

Вопрос

I have a tab in a form. On form load, I am getting text from a text file line by line and displaying them as labels on a form Tabcontrol Tabpage along with dynamically displaying buttons beside them. Now on those buttons click I want to copy the text in the associated labels. Can anyone suggest what to put in the Nextbtn_Click event?

Dim FILE_NAME As String = "D:\1.txt"    
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim i As Integer = 1
    For Each line As String In System.IO.File.ReadAllLines(FILE_NAME)
        Dim NextLabel As New Label
        Dim Nextbtn As New Button
        NextLabel.Text = line
        Nextbtn.Text = "Copy"
        NextLabel.Height = 22
        Nextbtn.Width = 55
        Nextbtn.Height = 22
        NextLabel.BackColor = Color.Yellow
        TabPage2.Controls.Add(NextLabel)
        TabPage2.Controls.Add(Nextbtn)
        NextLabel.Location = New Point(10, 10 * i + ((i - 1) * NextLabel.Height))
        Nextbtn.Location = New Point(120, 10 * i + ((i - 1) * Nextbtn.Height))
        AddHandler Nextbtn.Click, AddressOf Me.Nextbtn_Click
        i += 1
    Next
End Sub

Private Sub Nextbtn_Click(sender As Object, e As EventArgs)

End Sub
Это было полезно?

Решение

Store the assc. label in the tag property and you can cast it back when you click on the button. The sender object is the button that is currently clicked.

Dim FILE_NAME As String = "D:\1.txt"    
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim i As Integer = 1
    For Each line As String In System.IO.File.ReadAllLines(FILE_NAME)
        Dim NextLabel As New Label
        Dim Nextbtn As New Button
        Nextbtn.Tag = NextLabel
        NextLabel.Text = line
        Nextbtn.Text = "Copy"
        NextLabel.Height = 22
        Nextbtn.Width = 55
        Nextbtn.Height = 22
        NextLabel.BackColor = Color.Yellow
        TabPage2.Controls.Add(NextLabel)
        TabPage2.Controls.Add(Nextbtn)
        NextLabel.Location = New Point(10, 10 * i + ((i - 1) * NextLabel.Height))
        Nextbtn.Location = New Point(120, 10 * i + ((i - 1) * Nextbtn.Height))
        AddHandler Nextbtn.Click, AddressOf Me.Nextbtn_Click
        i += 1
    Next
End Sub

Private Sub Nextbtn_Click(sender As Object, e As EventArgs)
    Dim s As String = DirectCast(DirectCast(sender, Button).Tag, Label).Text
End Sub

Другие советы

Private Sub Clicked(ByVal sender As Object, ByVal e As EventArgs)
    Dim b As Button = DirectCast(sender, Button)
    TextBox2.Text = b.Name
    Clipboard.SetText(b.Name)

End Sub
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top