I. Preparation and use of class documents.
You can use this class by creating a separate class file (using Notepad) and then including it in your project, using the class's namespace.
How do I include a class file in a project?
1. Create a new folder in the project;
2. Place the class file in this folder;
3. In the VS Interface Solution Explorer, click the "Show All Files" button, then select the files, right-click "included in the project";
4. After referencing namespaces elsewhere in the project, you can use these classes.
Second, the production of login window
We can use a class file generator (code Smith) to help us make the classes we need, followed by the classes generated by the template after the table using Code Smith to connect to the database.
Click to login
//Click the login button Private voidButton1_Click (Objectsender, EventArgs e) { stringUserName =Textuser.text; stringPWD =Textpwd.text; //call method, Access database, check dataLogindata Data=NewLoginda (). Select (UserName, PWD); //If you access the data, the main window pops up if(Data! =NULL) {Main F=NewMain (); F.show (); } Else{MessageBox.Show ("Logon Failure"); } }
Third, catch the exception
This is the query data method in a class file,
Put the possible problem steps in the try, if there is an exception (for example, a connection to the database network problems), into the catch, we can choose to throw this exception or other operations. Finally inside is the statement that is not affected by the exception and is always executed.
//access the database based on the user name and password entered PublicLogindata Select (stringUserName,stringPWD) {Logindata Data=NULL; _cmd.commandtext="SELECT * FROM login where userName = @userName and [email protected]"; _cmd.parameters.clear (); _cmd.parameters.addwithvalue ("@userName", UserName); _cmd.parameters.addwithvalue ("@userPwd", PWD); Try{_conn.open (); SqlDataReader Dr=_cmd.executereader (); while(Dr. Read ()) {Data=NewLogindata (); Data. UserName= (String) dr["UserName"]; Data. Userpwd= (String) dr["userpwd"]; Data. Useridentity= (String) dr["useridentity"]; } Dr. Close (); Dr. Dispose (); } Catch(Exception ex) {Throwex; } finally{_conn.close (); _cmd.dispose (); _conn.dispose (); } returndata; }
The following is the result of calling the above method after shutting down the database service (throws an exception)
Third, hide Login window
if NULL ) { new Main (); This false; // Setting the Login window is not visible this. Owner = f; // Set as a child window of the main window, and the login window closes when the main window is closed F.windowstate = formwindowstate.maximized; // maximize the main window after logging in f.show (); }
Four, in the main window implementation "welcome you, XXX"
Code:
Overriding the constructor of the main window
When you create the main window, pass the user name to the constructor
C # Login window (Access database) production, the production and use of class files