lukas.kurka
lukas.kurka

Reputation: 45

WPF C# adding event handler programmatically

In my code I create an array of TextBoxes :

namespace TCalc
{
    public partial class MainWindow : Window
    {
        public TextBox[] pubAltArray;

        public MainWindow()
        {
            InitializeComponent();

            pubAltArray = new TextBox[10];

Then I create the TextBoxes programmatically using the following code :

private void generatePublishedTxtBox()
{
    for (int i = 0; i < 10; i++)
    {
        TextBox pubAlt = new TextBox();
        grid_profile.Children.Add(pubAlt);
        pubAlt.SetValue(Grid.RowProperty, 1);
        ...
        pubAltArray[i] = pubAlt;
    }
}

Than I have some routine I want to run when the content of each TextBox changes :

private void doTheStuff(object sender, TextChangedEventArgs e)
{
...
} 

So I tried to add event handler during the definition of new TextBox however without success :

pubAlt.TextChanged += new System.EventHandler(doTheStuff());

or

pubAlt.TextChanged += RoutedEventHandler(calculateCorAlts());

Any hint for me?

Upvotes: 2

Views: 4529

Answers (2)

123 456 789 0
123 456 789 0

Reputation: 10865

You are invoking the method using (). Change your code to be like this:

pubAlt.TextChanged += new System.EventHandler((s,e) => doTheStuff());
pubAlt.TextChanged += RoutedEventHandler((s,e) =>calculateCorAlts());

Your method are not matching what it was asking for.

Upvotes: 0

K Mehta
K Mehta

Reputation: 10553

Try:

pubAlt.TextChanged += new TextChangedEventHandler(doTheStuff);

or:

pubAlt.TextChanged += doTheStuff;

Both lines do the same thing. The second one is just shorthand for the first line since it makes code easier to read.

Upvotes: 2

Related Questions