I am new to windows Forms and didn't know about user control. I have a form 1 with a label and want to change the value of the label using user control. I also called user control in form1. I tested the form function using the usercontrol_click event. It shows the message box but not changing the label value.
Form 1 user control name flowLayoutPanel1 user control name ListView
private void ListItem_Click(object sender, EventArgs e)
{
Form1 a = new Form1();
//a.emailbody();
a.label5.Text = "work";
}
public void emailbody()
{
MessageBox.Show("Welcome");
}
CodePudding user response:
You are creating a new form with Form1 a = new Form1();
in the click event handler, but you never show this form using a.Show();
or a.ShowDialog()
.
Did you intend to set the label on the current form? If yes, then don't create a new form.
private void ListItem_Click(object sender, EventArgs e)
{
// Uses label in this form:
label5.Text = "work";
}
You simply write emailbody();
to call a method on the current form.
If you intended to set the label on another form that was already open, you need a reference to this form. E.g. you can store it in a field in the current form
private Form1 _form1;
private void OpenOtherFormButton_Click(object sender, EventArgs e)
{
_form1 = new Form1();
_form1.Show();
}
private void ListItem_Click(object sender, EventArgs e)
{
if (_form1 is not null) {
_form1.label5.Text = "work";
}
}
If you want to change the label of your user control, the label must be public. Assuming that the user control is on your form, do something like this:
myUserControl.label5.Text = "work";
If it is on another form, the user control must be public as well:
_form1.myUserControl.label5.Text = "work";
if the user control is on the panel:
flowLayoutPanel1.myUserControl.label5.Text = "work";
If the user control is on the same form as where the label is and ListItem_Click
is in the user control, then you must get reference to the form first.
// In the user control
var form1 = FindForm() as Form1;
if (form1 is not null) {
form1.label5.Text = "work";
}