Search code examples
vb.nettextbox

Get textbox from Button Tag


I try to get a TextBox from a Button.Tag.

I have X buttons and for every Button has a own TextBox.

Not I want one Click-Method for all buttons and get the correct TextBox from the Button.Tag, but this does not work.

Can someone help me with this?

 Dim Textbox As TextBox = CType(DirectCast(sender, Button).Tag, TextBox)
 Textbox.Text = ""

With this code I get the following exception:

System.InvalidCastException: "Das Objekt des Typs "System.String" kann nicht in Typ "System.Windows.Forms.TextBox" umgewandelt werden."


Solution

  • Your code tries to convert a String (name of the TextBox) into a TextBox, which won't work.

    So you either have to assign the TextBox'es by code like this:

    Button1.Tag = TextBox1
    Button2.Tag = TextBox2
    ...
    

    or find the TextBox by its name like this:

    Dim Textboxname As String = DirectCast(sender, Button).Tag.ToString()
    Dim Textbox As TextBox = DirectCast(Me.Controls.Find(Textboxname, True).First(), TextBox)
    Textbox.Text = ""