Finding the parent'control

Shaifali jain 420 Reputation points
2023-09-29T09:29:12.81+00:00

Hello ,
i am trying to find out the label control on the parent form and set its text property from the child form . to do this , i had tried many approaches and even set the modifier of that label to public but still can't access it . pls correct my code .

  public partial class login : blackborder_lightform
    {
        public login()
        {
            InitializeComponent();
        }

        private void login_Load(object sender, EventArgs e)
        {
            // Access the parent form
           // Form parent = (Form)this.Owner;   
         //  Label label = this.Parent.Labels["Label1"];
            parent.CurrentForm.Text = "Login Form is in focus "; 
            label1.Text += "Dummy";
            this.ActiveControl = textBox1;
        }
Developer technologies | Windows Forms
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. KOZ6.0 6,655 Reputation points
    2023-09-29T11:34:38.04+00:00

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-09-29T19:01:06.85+00:00

    Although you have an answer there is a better way using a delegate/event. This way there is zero need to find the label.

    Take sometime to learn about delegates/events as they extremely helpful in more ways than shown below. Also note, in the code below I pass a string, you can pass anything you want like an instance of a class or a number, bool etc.

    In regards to subscribing to events, check out Microsoft docs How to subscribe to and unsubscribe from events (C# Programming Guide)

    Child form

    public partial class Form2 : Form
    {
        public delegate void ChangeLabelText(string sender);
        public event ChangeLabelText OnChangeLabelText;
        public Form2()
        {
            InitializeComponent();
        }
    
        private void UpdateButton_Click(object sender, EventArgs e)
        {
            OnChangeLabelText!.Invoke(textBox1.Text);
        }
    }
    

    Parent form, in a button click event

    private void button3_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();
        form2.OnChangeLabelText += Form2_OnChangeLabelText;
        form2.Show();
    }
    
    private void Form2_OnChangeLabelText(string sender)
    {
        label1.Text = sender;
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.