First, I can't think of any good design that should lead to you doing this. If you need to do this in a real application,
If you know the button and the text box are the only controls on the form, you can cycle through all the controls on the form, ie:
Code:
public void ButtonClick(object sender, EventArgs e)
{
// I can't remember if the property is called "Parent" or "Container":
Form theForm = ((Control)sender).Parent;
TextBox theTextBox;
foreach (Control c in theForm.Controls)
{
if (c is TextBox)
{
theTextBox = (TextBox)c;
}
}
if (theTextBox != null)
{
MessageBox.Show("Woohoo, the text is: " + theTextBox.Text);
}
}
However, that's a disgusting solution.
A better OOP way is to create a form that inherits from System.Windows.Forms, which exposes two things:
Code:
public class QuestionForm : Form
{
// Expose an event people can subscribe to to know when the button is clicked:
public EventHandler ButtonClicked;
// Expose the contents of the text box as a property of the form
public string Answer
{
get
{
return textBox1.Text;
}
}
// Rest of windows forms code:
private TextBox textBox1;
private Button button1;
public QuestionForm()
{
textBox1 = new TextBox();
button1 = new Button();
textBox1.Text = "Type here, sucker!";
button1.Text = "Click this!";
button1.Click += new EventHandler(button1_Click);
this.Controls.Add(textBox1);
this.Controls.Add(button1);
}
private void button1_Click(object sender, EventArgs e)
{
// Fire our event handler to let other forms know the button was clicked
if (ButtonClicked != null)
{
ButtonClicked(this, EventArgs.Empty);
}
}
}
public class Program
{
public static void Main(string[] args)
{
QuestionForm qf = new QuestionForm();
qf.ButtonClicked += new EventHandler(OnButtonClicked);
qf.Show();
}
public void OnButtonClicked(object sender, EventArgs e)
{
// Someone clicked the button on the other form
QuestionForm qf = (QuestionForm)sender;
MessageBox.Show("Answer is: " + qf.Answer);
}
}
The idea is forms should be self containing - trying to access their controls from outside of the form goes against everything OOP stands for. If you need what's inside, have the form expose properties and events to "bubble up" other events (this is similar to what happens when you fart in the bath).
Edit: Sorry, I just read you didn't want to make a new form.
The first method is yucky because if you add another text box, there will be problems, and it's not very efficient. The second method is much more desirable, but you must have reasons for not doing it.
Another method might be to use the Tag property on the text box to uniqely identify the text box. Just assign a string to the textbox's Tag property, and test in the loop that the tag is what is expected.
Mind if I ask why you don't want to create a new form?