Passing control name to a method in vs2005

R

Ryan

How do I pass a control name to a method?
I have a Textbox named txt1; in the form load event I want to pass txt1 to a
method as:

private void MyForm_Load(object sender, EventArgs e)
{
MyMethod(txt1)
}

private Void MyMethod(txt1)
}
txt1.text = "My Value";
}
 
I

Ignacio Machin ( .NET/ C# MVP )

How do I pass a control name to a method?
I have a Textbox named txt1;

How it's named? notice that is not the same set the ID="XXXX" in the
aspx.

also note in your code that you use everywere the same name txt1. This
can lead to error or confusion.
If txt1 is a member of the class, then you do not need to pass it as a
parameter to MyMethod
 
D

DaveL

Ryan said:
How do I pass a control name to a method?
I have a Textbox named txt1; in the form load event I want to pass txt1 to
a
method as:

private void MyForm_Load(object sender, EventArgs e)
{
MyMethod(txt1)
}

private Void MyMethod(txt1)
}
txt1.text = "My Value";
}


you could do the below
namespace TestForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
MyMethod(this.txt1,null);
}

private void MyMethod(object Sender,EventArgs e)
{
Control oControl;
if (Sender is TextBox)
{
oControl = (TextBox)Sender;
Console.WriteLine(oControl.Text);
// Result Hello world

}
}

}
}
 
R

Ryan

Thanks, it worked.

DaveL said:
you could do the below
namespace TestForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
MyMethod(this.txt1,null);
}

private void MyMethod(object Sender,EventArgs e)
{
Control oControl;
if (Sender is TextBox)
{
oControl = (TextBox)Sender;
Console.WriteLine(oControl.Text);
// Result Hello world

}
}

}
}
 
B

Ben Voigt [C++ MVP]

you could do the below
namespace TestForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
MyMethod(this.txt1,null);

Better to use EventArgs.Empty instead of null.
}

private void MyMethod(object Sender,EventArgs e)

Second parameter isn't needed, but ok if this function needs to also be
wired to events
 

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