views:

78

answers:

4

I have a C# application and I am trying to prevent a form to show up in the constructor.

I launch the form like this:

Form1 f = new Form1();
f.ShowDialog();

what do I have to do in the Constructor so the f.ShowDialog should not launch and continue code execution.

+1  A: 

Can't you add a public property (ShowTheDialog in this example) in the constructor for f and set to true if you want to call f.ShowDialog

Form1 f = new Form1();
if(f.ShowTheDialog) {
  f.ShowDialog();
}
Nifle
A: 

(I'm no windows forms expert, but) couldn't you set a flag in your constructor, whether the form can be shown or not, then override the OnLoad() method, and if your flag is false, hide the form immediately, e.g:

private bool _canShow = true;
public Form1()
{
  _canShow = ...;
}

protected override OnLoad(EventArgs e)
{
  if (!_canShow) Close();
  base.OnLoad(e);
}
M4N
A: 

I think Pentium10 wants to be able to specify via the constructor whether, at a later time, ShowDialog is allows to actually display a dialog. In other words, he really wants to be able to override ShowDialog, so that in his own ShowDialog he can check this magic permission variable and either bail, or call the base ShowDialog.

I'm not sure if this is technically correct, but it does seem to work. Pentium10, in your Window class, create another public method called ShowDialog that hides the inherited ShowDialog. Then inside, check your variable and only if it's allowed, call the base's ShowDialog method, like this:

public partial class Window3 : Window
{
    bool _allowed { get; set; }
    public Window3( bool allowed)
    {
        _allowed = allowed;
        InitializeComponent();
    }

    public void ShowDialog()
    {
        if( !_allowed)
            return;
        else
            base.ShowDialog();
    }
}
Dave
Things like that might work, but I'd consider this to be a code smell. A method named `ShowDialog` should show a dialog and not simply do nothing, especially if this is the behavior expected throughout the framework.
0xA3
Agreed. I'm just offering the exact solution he wants, even though it's probably best dealt with differently.
Dave
Yes, I think already the original question sounds a bit like a code smell (with the little information we know).
0xA3
A: 

How about calling ShowDialog in the constructor itself if it needs to be shown ?

And then you only need to do:

Form1 f = new Form1();
slayerIQ