Viva
Viva

Reputation: 2075

how to create events on dynamic `textboxes`

I managed to create textboxes that are created at runtime on every button click. I want the text from textboxes to disappear when I click on them. I know how to create events, but not for dynamically created textboxes.

How would I wire this up to my new textboxes?

private void buttonClear_Text(object sender, EventArgs e)
{
    myText.Text = "";
}

Upvotes: 2

Views: 10089

Answers (6)

Parimal Raj
Parimal Raj

Reputation: 20575

This should do the job :

    private void button2_Click(object sender, EventArgs e)
    {
        Button btn = new Button();
        this.Controls.Add(btn);

        // adtionally set the button location & position

        //register the click handler
        btn.Click += OnClickOfDynamicButton;
    }

    private void OnClickOfDynamicButton(object sender, EventArgs eventArgs)
    {
        //since you dont not need to know which of the created button is click, you just need the text to be ""
        ((Button) sender).Text = string.Empty;
    }

Upvotes: 1

Stephen Binns
Stephen Binns

Reputation: 765

The sender parameter here should be the textbox which sent the even you will need to cast it to the correct control type and set the text as normal

if (sender is TextBox) {
     ((TextBox)sender).Text = "";
}

To register the event to the textbox

myText.Click  += new System.EventHandler(buttonClear_Text);

Upvotes: 5

spajce
spajce

Reputation: 7082

I guess the OP wants to clear all the text from the created textBoxes

private void buttonClear_Text(object sender, EventArgs e)
{
  ClearSpace(this);
}

public static void ClearSpace(Control control)
{
    foreach (var c in control.Controls.OfType<TextBox>())
    {
        (c).Clear();
        if (c.HasChildren)
            ClearSpace(c);
    }
}

Upvotes: 1

Arno Saxena
Arno Saxena

Reputation: 136

when you create the textBoxObj:

RoutedEventHandler reh = new RoutedEventHandler(buttonClear_Text);
textBoxObj.Click += reh;

and I think (not 100% sure) you have to change the listener to

private void buttonClear_Text(object sender, RoutedEventArgs e)
{
  ...
}

Upvotes: 1

Abdusalam Ben Haj
Abdusalam Ben Haj

Reputation: 5423

This is how you assign the event handler for every newly created textbox :

myTextbox.Click  += new System.EventHandler(buttonClear_Text);

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1500525

Your question isn't very clear, but I suspect you just need to use the sender parameter:

private void buttonClear_Text(object sender, EventArgs e)
{
    TextBox textBox = (TextBox) sender;
    textBox.Text = "";
}

(The name of the method isn't particularly clear here, but as the question isn't either, I wasn't able to suggest a better one...)

Upvotes: 2

Related Questions