I am having a difficult time creating an if statement in my program.cs file.
What I want to do is, before the main form (say Form1) loads, I want the program to check to make sure there is, or is not any information within my SQL database Tabel1. If there is information load Form2. If not, load Form1. (Form2 collects information and saves it into SQL database). Form1 is the default form to load. The main form. However, form1 needs information from SQL database in order to load.
I have tried this several different ways.
1. Created a hidden form upon start up where the form upon load, searches out the SQL database and sees if there is information in there or now.
2. Made a method within Form1 to check to see if information is within SQL database. If not, Form2 would load.
3. Program.cs file that opens sql database and searches out to see if there is data within the database table. if null, do this, else, do that.
I havent gotten anything to work. Here is what I have in my program.cs file.
public void OpenDatabase() { try { sqlcon.Open(); } catch (SqlException ex) { throw new Exception("Problem opening database"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } static SqlConnection sqlcon; public void Main1() { sqlcon = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\NewFPDB.mdf;Integrated Security=SSPI;User ID=FPDB_Admin;Password=123456;Persist Security Info=True;Connect Timeout=30;User Instance=False;"); SqlCommand command = new SqlCommand ("SELECT AirportID from Airports", sqlcon); OpenDatabase(); // Get the data reader SqlDataReader reader = command.ExecuteReader(); // Process each result reader.Read(); if (reader != null) { MessageBox.Show("1"); Application.Run(new Form1()); sqlcon.Close(); } else { Application.Run(new Form2()); sqlcon.Close(); } reader.Close(); sqlcon.Close(); } [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); sqlcon = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\NewFPDB.mdf;Integrated Security=SSPI;User ID=FPDB_Admin;Password=123456;Persist Security Info=True;Connect Timeout=30;User Instance=False;");
sqlcon.Open();
SqlCommand command = new SqlCommand ("SELECT UserID from Users", sqlcon);
// Get the data reader SqlDataReader reader = command.ExecuteReader(); // Process each result reader.Read(); if (reader != null) { //MessageBox.Show("1"); Application.Run(new Form1()); sqlcon.Close(); } else { Application.Run(new Form2()); sqlcon.Close(); } // Close the reader and the connection reader.Close(); sqlcon.Close(); }
|
Can anyone please help me out and let me know where ive gone wrong. I am just tring to
open up the database table, read it and if null, return form2. If data is present, load form1.
Thanks.
Ivan