1

I've read some other questions but I couldn't figure out how to solve my problem.

I have two forms in my application. frmMain and frmAdd. I want to open frmAdd from main form with a parameter to use in frmAdd.The below code i have tried

frmMain

frmAdd frm= new frmAdd("A");
frm.ShowDialog();

frmAdd

if (parameter=="A")
   //Do this
else if(parameter=="B")
  //Do that

How can I make it work?

public partial class frmAdd : Form
{
   public frmAdd() //Should I add somthing here?
   {
      InitializeComponent();
   }
}
Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
Ghasem
  • 14,455
  • 21
  • 138
  • 171
  • "read some other questions " - not clear what other question you've found, linked [duplicate](http://stackoverflow.com/questions/4247807/passing-variable-between-winforms) looks pretty close to what you want - read and comment what you don't understand (rather than simply stating [clinically tested](http://xkcd.com/1096/)). – Alexei Levenkov Jan 07 '15 at 07:21

1 Answers1

0

You can add parameterized constructor so that the form could be created with parameter and use this() to call the parameterless constructor

public partial class frmAdd : Form
    {
        public frmAdd() //Should I add somthing here?
        {
            InitializeComponent();
        }
        public frmAdd(string str) : this()
        {

        }
}
Adil
  • 146,340
  • 25
  • 209
  • 204
  • It works but `InitializeComponent();` has to be included in `public frmAdd(string str) : this()` – Ghasem Jan 07 '15 at 08:35
  • @AlexJolig, nope, `this()` part will ensure parameterless constructor will be called first, which contains `InitializeComponents()` already. Removing parameterless constructor is bad idea. – Sinatr Jan 07 '15 at 09:05
  • @Sinatr But my form has no controls and `form_load` event when showing up untill I added `InitializeComponents()` to `public frmAdd(string str) : this()` – Ghasem Jan 07 '15 at 09:49
  • You've made a mistake somewhere: either you forgot to add `this()` to a new constructor with parameter or you removed `InitializeComponents()` from parameterless constructor. – Sinatr Jan 07 '15 at 09:55