Mtok
Mtok

Reputation: 1630

How to stop loading a form in constructor in C# form application

I have 2 forms. I get the requested data to connect to database in Form1, send it to Form2, show Form2 and fill the datagridview in constructor of Form2 after connecting to database. Here I check if there is any rows in sdr (SqlDataReader). If not, what I want to do is stopping the Form2 to be loaded and turn back to Form1.

I tried this.close() but it doesn't work while executing the constructor of Form2.

if (!sdr.HasRows)
   {
      MessageBox.Show("No Data!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
      this.Close();
   }

Any ideas ?

Upvotes: 1

Views: 1403

Answers (2)

hometoast
hometoast

Reputation: 11782

Why not simply do your check before showing the form? Form1 has the data necessary to make the decision.

if(!sdr.HasRows)
  //show error
else    
  //show form2.

Upvotes: 1

Tigran
Tigran

Reputation: 62248

The closing and in general loading of the data has not to be done inside ctor of the Form, but inside Form.Load event.

For example:

//Form2.cs 



 public class Form2 : Form
 {
    ..... 

    public override OnLoad(EventArgs e)
    { 
       ......
       if (!sdr.HasRows)
       {
          MessageBox.Show("No Data!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
          this.Close();
        }
    }   


  }

Upvotes: 3

Related Questions