0

I have a code like

void onDgvRelations_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex == 2 && ktlg == null)
    {
        this.Cursor = Cursors.WaitCursor;
        ktlg = new FormKatalog();
        ktlg.Show();
        this.Cursor = Cursors.Default;
    }
}

The idea is to check if a form

FormKatalog ktlg

is closed. If it's closed I have to create a new form and show it to user. The problem is that after user close the form, variable ktlg will never be null.

How to check properly if a form was not instantiated OR was closed by user?

TOP KEK
  • 2,593
  • 5
  • 36
  • 62
  • possible duplicate of [c# how check if the form is already open, and close it if it does?](http://stackoverflow.com/questions/3861602/c-sharp-how-check-if-the-form-is-already-open-and-close-it-if-it-does) – jgauffin Mar 19 '12 at 11:25

3 Answers3

3

You can use custom bool switch and set it in Form.Closed Event handler

// on the class level
private bool isClosed = false;

void OnCellMouseClick(object sender, DataGridViewCellMouseEventArgs e) 
{    
   if (e.ColumnIndex == 2 && (ktlg == null || this.isClosed))     
   { 
        this.Cursor = Cursors.WaitCursor
        if (ktlg == null)
        {
           ktlg = new FormKatalog();
           ktlg.FormClosed += (s, e) => this.isClosed = true;
        }

        this.isClosed = false;
        ktlg.Show();         
        this.Cursor = Cursors.Default; 
   }
}
sll
  • 61,540
  • 22
  • 104
  • 156
2

I assume the ktlg variable is a class member? Then you could do the following:

void onDgvRelations_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex == 2 && ktlg == null)
    {
        this.Cursor = Cursors.WaitCursor;

        if (ktlg == null)
        {
            ktlg = new FormKatalog();
            ktlg.FormClosed +=  (sender, e) => ktlg = null;
            ktlg.Show();
        }
        else
            ktlg.BringToFront();

        this.Cursor = Cursors.Default;
    }
}
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
  • Why you instantiating a new form when `ktlg != null`? Also you've copypasted typo from my initial answer ;) `(**0**, e)` - zero is not right name :) – sll Mar 19 '12 at 11:24
  • 1
    Control goes into the first `if` only when `ktlg` is `null`, so code inside `if (ktlg != null)` is unreachable. – Saeb Amini Mar 19 '12 at 11:28
  • @sll: Yes, I did a quick copy & paste. Originally I wanted the OP to assign a "real" event handler, but then I saw your lambda expression, which is far more elegant ;-) – Thorsten Dittmar Mar 19 '12 at 11:36
  • +1 Anyway your approach is right, BTW, thanks for an NullRef Ex observation :) – sll Mar 19 '12 at 12:00
1

There is an "On Form Closing" event which you could use.

Its a bit cheaty but you could set a flag when the user closes the form (and revert it onFormLoad)

Haedrian
  • 4,240
  • 2
  • 32
  • 53