Search code examples
c#async-awaitloadpanelwait

Wait Form C# On Panel


I have 3 forms. Names: MainScreen, LoadingForm, MoviesInfo. When I press the button on the MainScreen, it is doing some works and the LoadingForm is loading inside a panel on the MainScreen.I want to do when works done, show the MoviesInfo Form on the same panel on the MainScreen or panel on the LoadingForm. How can I do that? I add the forms on the panel like that.

public static void AddFormToPanel(Form frm, Panel panel)
        {
            frm.TopLevel = false;
            panel.Controls.Add(frm);
            frm.Show();
            frm.Dock = DockStyle.Fill;
            frm.BringToFront();
        }

//Loading Form
public partial class LoadingForm : Form
    {
        public Action Worker { get; set; }
        public LoadingForm(Action worker)
        {
            InitializeComponent();
            if (worker == null)
            {
                throw new ArgumentNullException();

            }
            Worker = worker;

        }
        private void btnCancel_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Task.Factory.StartNew(Worker)
                .ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
        }


    }

MainScreen Form

    private void MovieOnButtonClick(object sender, EventArgs eventArgs)
            {


  using (loading = new LoadingForm(getMovieData))
        {
            loading.ShowDialog(this);
        }

       AddFormToPanel(moviesInfo, panelMain);


            }

I don't want this line loading.ShowDialog(this); I want to add loading form inside the panel.


Solution

  • Move the action and the control to the MainForm:

    private async void MovieOnButtonClick(object sender, EventArgs eventArgs)
    {
        var loadingForm = new LoadingForm();    // create a dummy loadingForm
        AddFormToPanel(loadingForm, panelMain);  
    
        var work = Task.Factory.StartNew(Worker);   // Worker = GetMovies or so
        await work;
    
        AddFormToPanel(moviesInfo, panelMain);    
        loadingForm.Dispose();
    }
    

    Remove all logic and events from the LoadingForm.

    And it is better to use UserControl than Forms to place in that Panel.