Search code examples
c#eventsuser-controls

User Control BringToFront() Event?


I want to refresh a datagridview on my User Control, I call the user control with a BringToFront(); action on my main form, is there any event so I can refresh the datagridview once the User control is set to front? something like:

Custom Control: (Has datagridview: dgvCustomers)

namespace Healthcare
{
    public partial class Overview : UserControl
    {
        public Overview()
        {
            InitializeComponent();
        }

        public void RefreshGrid()
        {
            using (DatabaseContext db = new DatabaseContext())
            {
                customersBindingSource.DataSource = db.Customers.ToList();
            }
        }

        private void Overview_Load(object sender, EventArgs e)
        {
            RefreshGrid();
        }
    }
}

Main form:

private void btnOverview_Click(object sender, EventArgs e)
{
    ccOverview.BringToFront();
    txtTitle.Text = "Healthcare - Overview";
    RefreshGrid(); // Does not exist in the current context
}

Solution

  • It seems easier to just group these 2 methods together. Its simple its evident, its easily maintainable and you don't have to plumb up other events to do magic things

    Example

    public void RefreshMyAwesomeGrid()
    {
        using (DatabaseContext db = new DatabaseContext())
        {
            customersBindingSource.DataSource = db.Customers.ToList();
        }
    }
    
    ...
    
    MyUserControl.BringToFront();
    RefreshMyAwesomeGrid();
    

    Update

    The thing is that I can not acces the datagrid from my main form, on my main form I have a button and once that button is pressed it brings the user control to front so I have to put the datagridview refresh action in the User Control but I want to trigger it with a main form action

    Assuming your DataGrid is in your userControl... Unfortunately BringToFront cant be overridden. However, you have a couple of options.

    The simplest, would be just put a public method on your UserControl class RefreshMyAwesomeGrid. when you call BringToFront call RefreshMyAwesomeGrid

    Either that, or just make your OwnBringToFrontPlusRefresh <-- seems a bit meh though

    Or you could use decoupled messages depending on if you are using any frameworks

    Update 2

    Just dig in to your user control

    private void btnOverview_Click(object sender, EventArgs e)
    {
        ccOverview.BringToFront();
        txtTitle.Text = "Healthcare - Overview";
        ccOverview.RefreshGrid(); // exists now
    }