In visual studio how do you access a control on a form hosting a user control? For example, when text changes in a text-box in a user control, I want text in another text-box in another user control to change. Both these user controls are hosted on the same form. Thanks in advance!
How to access controls on hosted form in a user control WinForm
Asked Answered
Raise an event from your userControl, have the form or other UC subscribe to the event. Begs the question if they are that closely related, why are they on different controls? –
Napier
Can you be more specific? Why you need such integration between 2 controls at design time? –
Mcgrew
Plutonix, they are on separate controls because the user is able to decide which user control that want to display on the form. It could be either one or both. If both are displaying at the same time, the text needs to match. –
Palfrey
Reza, it is a SOAP client application that gives the user two different ways to enter data to make a request. –
Palfrey
If I need different UI for data entry, I prefer to have 2 controls with different UI, but I will use a single data source for them and handle the scenario using data-binding. If you bind both controls to a single data source, while you can have different UI, you have a single data and both controls data are sync. I shared a solution for your question :) –
Mcgrew
If you need different UI for data entry, I prefer to have 2 controls with different UI, but I will use a single data source for them and handle the scenario using data-binding.
If you bind both controls to a single data source, while you can have different UI, you have a single data and both controls data are sync.
The answer to your question:
You can define a property in each control which set Text
of TextBox
. Then you can handle TextChanged
event of the TextBox
and then find the other control and set the text property:
Control1
public partial class MyControl1 : UserControl
{
public MyControl1() { InitializeComponent(); }
public string TextBox1Text
{
get { return this.textBox1.Text; }
set { this.textBox1.Text = value; }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (Parent != null)
{
var control1 = Parent.Controls.OfType<MyControl2>().FirstOrDefault();
if (control1 != null && control1.TextBox1Text != this.textBox1.Text)
control1.TextBox1Text = this.textBox1.Text;
}
}
}
Control2
public partial class MyControl2 : UserControl
{
public MyControl2() { InitializeComponent(); }
public string TextBox1Text
{
get { return this.textBox1.Text; }
set { this.textBox1.Text = value; }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (Parent != null)
{
var control1 = Parent.Controls.OfType<MyControl1>().FirstOrDefault();
if (control1 != null)
control1.TextBox1Text = this.textBox1.Text;
}
}
}
Thanks so much! Works perfectly. –
Palfrey
© 2022 - 2024 — McMap. All rights reserved.