Passing control name to a method in vs2005

  • Thread starter Thread starter Ryan
  • Start date Start date
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";
}
 
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
 
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

}
}

}
}
 
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

}
}

}
}
 
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
 
Back
Top