Reputation: 1630
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
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
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