Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters in the Form constructor, winforms c#

I have a following inheritance hierarchy:

Class A : Form
Class B : Class A

Class A needs to be able to accept a parameter so that I can create the instance of Class B like this:

ClassB mynewFrm = new ClassB(param);

How do I define such a constructor in Class A?

thanks!

I am using Winforms in .net 3.5, c#

EDITED: Class A and Class B are defined as forms, using partial classes. So I guess this is turning into a question about partial classes and custom (overriden) constructors.

like image 657
sarsnake Avatar asked Jan 16 '23 09:01

sarsnake


1 Answers

Here is a complete demo sample that demostrates required behaviour.

For the sake of ease your learning, I chose a string type parameter that you adjust to your case.

To test it, create a new Visual Studio *C#* project and fill program.cs with the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Stackoverflow
{

    public class ClassA : Form
    {
        public ClassA()
        {
            InitializeComponent();
        }

        public ClassA(string WindowTitleParameter)
        {
            InitializeComponent();
            this.Text = WindowTitleParameter;
            MessageBox.Show("Hi! I am ClassB constructor and I have 1 argument. Clic OK and look at next windows title");
        }

        private void InitializeComponent() // Usually, this method is located on ClassA.Designer.cs partial class definition
        {
            // ClassA initialization code goes here
        }

    }

    public class ClassB : ClassA
    {
        // The following defition will prevent ClassA's construtor with no arguments from being runned
        public ClassB(string WindowTitleParameter) : base(WindowTitleParameter) 
        {
            InitializeComponent();
            //this.Text = WindowTitleParameter;
            //MessageBox.Show("Hi! I am ClassB constructor and I have 1 argument. Clic OK and look at next windows title");
        }

        private void InitializeComponent() // Usually, this method is located on ClassA.Designer.cs partial class definition
        {
            // ClassB initialization code goes here
        }

    }

    static class Program
    {
        /// <summary> 
        /// The main entry point for the application. 
        /// </summary> 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // If you debug this code using StepInto, you will notice that contructor of ClassA (argumentless)
            // will run prior to contructor of classB (1 argument)

            Application.Run(new ClassB("Look at me!"));
        }
    }
}
like image 54
Julio Nobre Avatar answered Jan 31 '23 08:01

Julio Nobre