Pass a Control name to an Event Handler

R

Ryan

I have the following code in vs2005; line number is added for convenience:

1 private void Form1_Load(object sender, EventArgs e)
2 {
3 txtMyField.Enabled = true;
4 Form2 f = new Form2();
5 f.DoUpdate += new Form2.UpdateHandler(MyForm2_ButtonClicked);
6 }

7 private void MyForm2_ButtonClicked(object sender, ValuesUpdateEventArgs3 e)
8 {
9 string sValues = "";
10 sValues = e.Val1;
11 txtMyField.Text = sValues;
12 }

Currently, my field name txtMyField.text is hardcoded and gets a value from
sValues (line #10).
Instead of hardcoding a fieldname as in Line #10; how do I pass the control
name on line #5 to event in Line #7?
Something like:

5 f.DoUpdate += new
Form2.UpdateHandler(MyForm2_ButtonClicked(txtMyField.Text));


Thanks in advance.
 
A

Alberto Poblacion

Ryan said:
I have the following code in vs2005; line number is added for convenience:

1 private void Form1_Load(object sender, EventArgs e)
2 {
3 txtMyField.Enabled = true;
4 Form2 f = new Form2();
5 f.DoUpdate += new Form2.UpdateHandler(MyForm2_ButtonClicked);
6 }

7 private void MyForm2_ButtonClicked(object sender,
ValuesUpdateEventArgs3 e)
8 {
9 string sValues = "";
10 sValues = e.Val1;
11 txtMyField.Text = sValues;
12 }

Currently, my field name txtMyField.text is hardcoded and gets a value
from
sValues (line #10).
Instead of hardcoding a fieldname as in Line #10; how do I pass the
control
name on line #5 to event in Line #7?
Something like:

5 f.DoUpdate += new
Form2.UpdateHandler(MyForm2_ButtonClicked(txtMyField.Text));

If you are using C# 2.0 or above, you can use an anonymous delegate to
"capture" the passed control. Something similar to the following (typed from
memry, untested):

5 f.DoUpdate += delegate(object sender, ValuesUpdateEventArgs3 e)
{ string sValues = ""; sValues = e.Val1; txtMyField.Text = sValues; };

Note that here you are "passing" txtMyField in Line 5 as you wanted. If
you need to reuse it in several places, you can move the code to a separate
metod and pass to it a reference to txtMyField:

5 f.DoUpdate += delegate(object sender, ValuesUpdateEventArgs3 e)
{ MyFunc(txtMyField,e); };

private void MyFunc(TextBox t, ValuesUpdateEventArgs3 e)
{
string sValues = "";
sValues = e.Val1;
t.Text = sValues;
}
 
R

Ryan

I have read similiar code on Developerdex.com but couldn't accomplish what I
was looking for. But, somehow, I was able to understand your language;
thanks for your help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top