Search code examples
c#winformsuser-controlsinitializationmessagebox

How do i show a new form from usercontrol?


I'm making a usercontrol which is a file manager (cut ,copy ,paste .. etc)
so while moving/coping files .. i had to show a messagebox when the file is already exist .. to let the user to confirm overwrite it or cancel .. but i need 4 buttons

  • [YES]
  • [YES TO ALL]
  • [NO]
  • [CANCEL]

    so i made a new form called "MyMessageBox" which contains the 4 buttons and a label.
    my problem is .. in (userControl1.cs) i can't initialize the form like this:

    MyMessageBox msgbox = new MyMessageBox("overwrite file ?");
    

  • Solution

  • First of all you need to make sure that your usercontrol has visibility of the form that you created(i.e. if your form is in another namespace or project you will need to use a using statement or add a project reference in order for your usercontrol to be able to use it.) and that your constructor is what you are thinking it is as M.Babcock is suggesting. You can try something like this

    UserControl:

    public partial class UserControl1 : UserControl
    {
        MyMessageBox msgbox; 
        public UserControl1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            msgbox  = new MyMessageBox("Overwrite File ?");
            msgbox.ShowDialog();
        }
    }
    

    CustomMessageBox:

    public partial class MyMessageBox : Form
    {
        public MyMessageBox( string Message)
        {
            InitializeComponent();
            label1.Text = Message;
        }
    
    }
    

    Which will give you a result like this.

    enter image description here