Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reach and set a control's property outside of a Form?

I am really new to programming and currently working on a C# Windows Forms application.

The problem is the following: I have a Form with different objects and controls like: tabpages, textboxes, timers, etc . I also have a UserControl form which I load into one of the main Form's tabpages.

I would like to write a code into the UserControl , how can I manipulate element properties of the main Form.

For example: when I click on a button on the UserControl form It sets the main Form's timer.Enabled control to true.

like image 494
szabolcsmolnar Avatar asked Jan 18 '26 18:01

szabolcsmolnar


1 Answers

It is possible to do this, but having the user control access and manipulate the form isn't the cleanest way - it would be better to have the user control raise an event and have the hosting form deal with the event. (e.g. on handling the button click, the form could enable/disable the timer, etc.)

That way you could use the user control in different ways for different forms if need be; and it makes it more obvious what is going on.

Update: Within your user control, you can declare an event - In the button click, you raise the event:

namespace WindowsFormsApplication1
{
    public partial class UserControl1 : UserControl
    {
        public event EventHandler OnButtonClicked;


        public UserControl1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            EventHandler handler = OnButtonClicked;

            // if something is listening for this event, let let them know it has occurred
            if (handler != null)
            {
                handler(this, new EventArgs());
            }

        }
    }
}

Then within your form, add the user control. You can then hook into the event:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            userControl11.OnButtonClicked += userControl11_OnButtonClicked;
        }

        void userControl11_OnButtonClicked(object sender, EventArgs e)
        {
            MessageBox.Show("got here");
        }


        }
    }
like image 154
NDJ Avatar answered Jan 20 '26 08:01

NDJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!