Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
831,61 KB
Nội dung
5.7 Bind Data to Associated Controls in LogIn Form 273 this new object and select the pass_word column by clicking on it. The data binding is done. Some readers may have noted that when we call the FillByUserNamePassWord() method, we fi ll the LogIn form with four columns; user_name, pass_word, faculty_id, and student_id from the LogIn table. In fact, we only fi ll two textbox controls on the form, txtUserName and txtPassWord, with two associated columns in the LogIn table, user_ name and pass_word. We only need to know if we can fi nd the matched username and password entered by the user from the LogIn table. If both matched items can be found from the LogIn table, the login is successful and we can continue to the next step. Two bound controls on the form, txtUserName and txtPassWord, will be fi lled with the identi- cal values stored in the LogIn table. It looks like this does not make sense. In fact, we do not want to retrieve any column from the LogIn table. Instead, we only want to fi nd the matched items of username and password from the LogIn table. If we can fi nd matched username and password, we do not care whether we fi ll the faculty_id and student_id or not. If no matched items can be found, this means that the login has failed and a warning message should be displayed. Before we can go ahead with our coding, one we need to point out the displaying style of the password in the textbox control txtPassWord. Generally, the password letters will be represented by a sequence of stars ( * ) when users enter them as the project is running. To make this happen in our project, we need to set the PasswordChar property of the textbox control txtPassWord to a star ( * ). To check the matched username and password entered by the user from the data source, one can use Return a Single Value to Query Data for LogIn table. But here in order to simplify this check, we use the Fill() method to fi ll four columns in a mapped data table in the DataSet. Then we can check whether this Fill() is successful. If it is, the matched data items have been found. Otherwise no matched data items are found. Now it is the time for us to develop codes that are related to the objects we created in the previous steps such as the BindingSource and TableAdapter to complete the dynamic query. The operation sequences of the LogIn form are as follows: 1. When the project runs, the user needs to enter the username and password to two textbox controls, txtUserName and txtPassWord. 2. Then the user will click on the LogIn button on the form to execute the LogIn button click method. 3. The LogIn button click method will fi rst create some local variables or objects that will be used for the data query and a new object for the next form. 4. Then the method will call the FillByUserNamePassWord() method to fi ll the LogIn form. 5. If this Fill is successful, which means that the matched data items for username and pass- word have been found from the LogIn table, the next window form, SelectionForm, will be displayed for the next step. 6. Otherwise, a warning message is displayed. c05.indd 273c05.indd 273 2/11/2010 2:58:07 PM2/11/2010 2:58:07 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 274 Chapter 5 Data Selection Query withVisual C#.NET As we discussed in Section 5.5.1 , these new created design tools, cSE_DEPTDataSet, logInTableAdapter, and logInBindingSource, are not the classes but the instances of design tools. Therefore we can directly use these instances to develop our code. Keeping this in mind, now let ’ s begin to develop the codes for the LogIn form. 5.8 DEVELOP CODES TO QUERY DATA USING FILL() METHOD Select the LogIn.cs from the Solution Explorer window and click on the View Designer button to open its graphical user interface. Double click on the LogIn button to open its Click method. First, we need to create a local object selForm, which is an instance of the SelectionForm class and then enter the codes shown in Figure 5.38 into this method. Let ’ s take a closer look at this piece of code to see how it works. A. A new namespace is created by the Visual C#, and the name of this namespace is equal to the name of our project, SelectWizard. By using the namespace technology, it is much easier to distinguish the different variables, methods, delegates, and events that have the same name but are located at different spaces. B. This line indicates that our LogIn form class is derived from the system class Form. C. The constructor of our LogIn form class contains a built - in method, InitializeComponent(). This method is used to initialize all new created instances and variables in this form. Starting Visual C# 2008, this method is moved to the LogIn.Designer.cs fi le. namespace SelectWizard { public partial class LogInForm : Form { public LogInForm() { InitializeComponent(); } private void cmdLogIn_Click(object sender, EventArgs e) { SelectionForm selForm = new SelectionForm(); logInTableAdapter.ClearBeforeFill = true; logInTableAdapter.FillByUserNamePassWord(cSE_DEPTDataSet.LogIn, txtUserName.Text, txtPassWord.Text); if (cSE_DEPTDataSet.LogIn.Count == 0) { MessageBox.Show("No matched username/password found!"); txtUserName.Clear(); txtUserName.Focus(); txtPassWord.Clear(); } else { selForm.Show(); this.Hide(); } } A B C D E F G H I SelectWizard.LogInForm cmdLogIn_Click Figure 5.38 Coding of the LogIn button Click method. c05.indd 274c05.indd 274 2/11/2010 2:58:07 PM2/11/2010 2:58:07 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 5.8 Develop Codes to Query Data Using Fill() Method 275 D. Our LogIn button ’ s Click method contains two arguments: The sender indicates the current object that triggers this method, and the second argument e contains the additional information for this event. E. As this method is triggered and executed, fi rst we need to create an instance of our next form window, SelectionForm. F. Before fi lling the LogIn data table, clean up that table in the DataSet. As we mentioned in Section 5.2.1.1 , the DataSet is a table holder and it contains multiple data tables. But these data tables are only mappings to those real data tables in the database. All data can be loaded into these tables in the DataSet by using the TableAdapter when the project runs. Here a property ClearBeforeFill , which belongs to the TableAdapter, is set to True to perform this cleaning job for that mapped LogIn data table in the DataSet. G. Now we need to call the Fill() method we created in Section 5.6 , exactly the FillByUserNamePassWord(), to fi ll the LogIn data table in the DataSet. Because we have already bound two textbox controls on the LogIn form, txtUserName and txtPassWord, with two columns in the LogIn data table in the DataSet, user_name and pass_word , by using the logInBindingSource, so these two fi lled columns in the LogIn data table will also be refl ected in those two bound textbox controls, txtUserName and txtPassWord, when this Fill() method is executed. This Fill() method has three arguments; the fi rst one is the data table, in this case it is the LogIn table that is held by the DataSet, CSE_DEPTDataSet. The following two parameters are dynamic parameters that were temporarily replaced by two question marks when we modifi ed this Fill() method in Section 5.6 . Now we can use two real parameters, txtUserName.Text and txtPassWord.Text, to replace those two question marks to com- plete this dynamic query. H. If no matched username and password can be found from the LogIn table in the database, the Fill() method cannot be executed to fi ll the LogIn table in the DataSet. This situation can be detected by checking the Count property of the LogIn table in the DataSet. This Count property represents the number of rows that have been successfully fi lled to the LogIn table in the DataSet. A zero value means that no matched username and password has been found and this fi ll has failed. A warning message is displayed if this happens and some cleaning jobs are performed for two textboxes in the LogIn form. By checking this property, we will know if this Fill is successful or not, or if a matched username and pass- word has been found from the database. I. Otherwise if a matched username and password is found from the LogIn table in the database and the login process is successful, the next window form, SelectionForm, will be displayed to allow users to continue to the next step. After displaying the next form, the current form, LogIn form, should be hidden by calling the Hide() method. The keyword this represents the current form. The coding for the Cancel button Click method is very simple. The Application.Exit() method should be called to terminate our project if this button is clicked by the user. Before we can test this piece of code by running the project, make sure that the LogIn form has been selected as the Startup form. To confi rm this, double click on the Program. cs folder from the Solution Explorer window to open the Main() method. Make sure that the argument of the Application.Run() method is new LogInForm(). This means that a new instance of LogInForm class is created and displayed as this Run() method is executed. Another important issue is that in order to run this login process properly, make sure to remove the LogInForm_Load() method and its content since a default Fill() method c05.indd 275c05.indd 275 2/11/2010 2:58:08 PM2/11/2010 2:58:08 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 276 Chapter 5 Data Selection Query withVisual C#.NET is included in this method, and both username and password textboxes will have been already fi lled before the LogIn button is clicked on by the user when the project runs; this method is executed fi rst when the project runs. Click on the Start button to run the project, and the running LogIn form should match the one shown in Figure 5.39 . Enter a valid username such as “ jhenry ” to the User Name textbox and a valid pass- word such as “ test ” to the Pass Word textbox, then click on the LogIn button. The FillByUserNamePassWord() method will be called to fi ll the LogIn table in the data source. Because we entered correct username and password, this fi ll will be successful and the next form, SelectionForm, will be shown up. Now try to enter a wrong username or password; then click on the LogIn button and a Messagebox will be displayed, which is shown in Figure 5.40 , to ask the user to handle this situation. In this section, we used the LogIn form and LogIn table to show readers how to perform a dynamic data query and fi ll a mapped data table in the DataSet by using the Visual Studio 2008 design tools and wizards. The coding is relatively simple and easy to follow. In the next section, we will show the readers how to use another method provided by the TableAdapter to pick up a single value from the database. 5.9 USE RETURN A SINGLE VALUE TO QUERY DATA FOR LOGIN FORM Many people have experienced forgetting either their username or their password when they try to logon to a specifi c website to get some information, to order some merchan- dises, or pay bills for their monthly utilities or cell phones. In this section, we show users how to retrieve a single data value from the database. This method belongs to the TableAdapter class. Figure 5.39 Running status of the project. Figure 5.40 Warning message. c05.indd 276c05.indd 276 2/11/2010 2:58:08 PM2/11/2010 2:58:08 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 5.9 Use Return a Single Value to Query Data for LogIn Form 277 We still use the LogIn form and LogIn table as an example. Suppose you forget your password, but you want to login to this project by using the LogIn form with your user- name. By using this example, you can retrieve your password by using your username. The DataSet Designer allows us to edit the structure of the DataSet. As we discussed in Section 5.6 , by using this Designer, you can confi gure an existing query, add a new query, and add a new column and even a new key to a database. The Add Query method allows us to add a new data query with a SQL SELECT statement, which returns a single value. Open the LogIn form window from the Solution Explorer window and open the Data Source window by clicking on the Data menu item from the menu bar. Right - click on any place inside that window and select the Edit DataSet with Designer, then locate the LogIn table and right - click on the last line of that table, which contains our modifi ed method FillByUserNamePassWord() we did in the last section. Then select Add Query to open the TableAdapter Query Confi guration Wizard. On the opened wizard, keep the default selection Use SQL Statements, which means that we want to build a query with SQL Statements, then click on the Next button and choose SELECT, which returns a single value radio button. Click on Next to go to the next window and click on the Query Builder button to build our query. On the opened Query Builder dialog, perform the following operations to create this single data query: • Click on the fi rst row from the second pane to select it. • Then right - click on this row and select Delete from the pop - up menu to delete this row. • Go to the top pane and select the pass_word and user_name columns from the LogIn table by checking two checkboxes related to those two columns. • Go to the second pane and uncheck the checkbox for the user_name column from the Output column since we do not want to use it as the output, but instead we need to use it as a criterion to fi lter this query. • Still in the second pane, right - click on the Group By column and select Delete from the pop - up menu to remove this Group By choice. • Type a question mark on the Filter fi eld in the user_name column, and press the Enter key on your keyboard. Your fi nished Query Builder should match the one shown in Figure 5.41 . The SQL statement SELECT pass_word FROM LogIn WHERE (user_name = @Param1) indicates that we want to select a password from the LogIn table based on the username, which is a dynamic parameter, and this parameter will be entered by the user when the project runs. Click on the OK button to go to the next window. The next window is used to confi rm your terminal SQL statement. Click on Next to go to the next window. This window allows you to choose a function name for this query. Change the default name to a meaningful name such as PassWordQuery, then click on the Next button. A successful Wizard Result will be displayed if everything is fi ne. Click on the Finish button to complete this confi guration. Now let ’ s do our coding for the LogIn form. For testing purposes, we need to add a temporary button with the name = cmdPW and the Text = Password to the LogIn form. Then select and open the LogIn form from the Solution Explorer window, double - click c05.indd 277c05.indd 277 2/11/2010 2:58:08 PM2/11/2010 2:58:08 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 278 Chapter 5 Data Selection Query withVisual C#.NET on the Password button to open its method, and enter the codes shown in Figure 5.42 into this method. Let ’ s have a little closer look at this piece of code. A. A local string variable passWord is created, and it is used to hold the returned queried single value of the pass_word. B. The query method we just built in this section, PassWordQuery(), with a dynamic param- eter username that is entered by the user is called to retrieve back the matched pass_word. C. If this query found a valid password from the LogIn table based on the username entered by the user, that password will be returned and displayed in a MessageBox. D. If this query cannot fi nd any matched pass_word, a blank string will be returned and assigned to the variable passWord. A Messagebox with a warning message will be dis- played if this situation happens. Figure 5.41 Finished Query Builder. private void cmdPW_Click(object sender, EventArgs e) { string passWord; logInTableAdapter.ClearBeforeFill = true; passWord = logInTableAdapter.PassWordQuery(txtUserName.Text); if (passWord != String.Empty) MessageBox.Show("The Password is: " + passWord); else MessageBox.Show("No matched password found!"); } A B C D kcilC_WPdmCmroFnIgoL.draziWtceleS Figure 5.42 Codes for the cmdPW button method. c05.indd 278c05.indd 278 2/11/2010 2:58:08 PM2/11/2010 2:58:08 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 5.9 Use Return a Single Value to Query Data for LogIn Form 279 Now let ’ s run the project to test this query. Click on the Start button to run the project, and your running project should match the one shown in Figure 5.43 . Enter a username such as “ ybai ” to the User Name box and click on the PassWord button. The returned password is displayed in a message box, which is shown in Figure 5.44 . Well, it looks like a fun! Does it not? Now you can remove the temporary PassWord button and its method from this LogIn form if you like since we do not need it any more for this project. Before we can move to the next section, we need to do one more thing, which is to add an accessing method for the LogInForm to allow other methods in the project to access the LogInForm easily when they need to perform some actions on it. For example, to close the LogInForm from other form windows, you need to call this method to access the LogInForm and call its Close() method. Open the Code Window of the LogInForm and add a new method named getLog- InForm() with the code shown in Figure 5.45 into the LogInForm class. When this method is called, a reference, this , is returned to the calling method. Generally, the reference this represents the current form object. In the following sections, we will show the readers how to develop more professional data - driven projects by using more controls and methods. We still use the SelectWizard example project and continue with the SelectionForm. Figure 5.43 Running status of the LogIn form. Figure 5.44 Returned password. public LogInForm getLogInForm() { return this; } SelectWizard.LogInForm getLogInForm() Figure 5.45 Coding for the getLogInForm method. c05.indd 279c05.indd 279 2/11/2010 2:58:11 PM2/11/2010 2:58:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 280 Chapter 5 Data Selection Query withVisual C#.NET 5.10 CODING FOR SELECTION FORM As we discussed in Section 5.8 , if the login process is successful, the SelectionForm window should be displayed to allow users to continue to the next step. Figure 5.46 shows an opened SelectionForm window. All information in the ComboBox control is associated with a form window. Furthermore it is associated with a group of data stored in a data table in the database. The operation steps for this form are summarized as follows: 1. When this form is opened, three pieces of information will be displayed in a ComboBox control to allow users to make a selection to browse the information related to that selection. 2. When the user clicks the OK button, the selected form should be displayed to enable the user to browse the related information. Based on the operation step 1, the codes for displaying three pieces of information should be located in the constructor of the SelectionForm since this constructor should be called fi rst as an instance of the SelectiionForm is created. Open the SelectionForm window and click on the View Code button to open its code window. Enter the following codes, which are shown in Figure 5.47 , into the constructor of the SelectionForm. Let ’ s see how this piece of code works. A. Three instances are created fi rst, and each one is associated with a Form class. B. The Add() method of the ComboBox class is used to attach all three pieces of information to this ComboBox. The reference this represents the current form object, an instance of the SelectionForm class, and the property SelectedIndex is set to zero to select the fi rst information as the default one. According to operation step 2 above, when users click on the OK button, the related form selected by the user should be displayed to allow users to browse information from that form. Click the View Designer button to open the graphical user interface of the SelectionForm object. Then double - click on the OK button to open its cmdOK_Click method and enter following codes shown in Figure 5.48 into this method. Let ’ s see how this piece of code works. The function for this piece of coding is straightforward and easy to be understood, which is explained as follows: Figure 5.46 Selection Form. c05.indd 280c05.indd 280 2/11/2010 2:58:12 PM2/11/2010 2:58:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 5.10 Coding for Selection Form 281 A. Open the FacultyForm window if the user selected Faculty Information. B. Open the StudentForm window if the user selected Student Information. C. Open the CourseForm window if the user selected Course Information. D. An error message is displayed if no information is selected. The last coding for this form is the Exit button. Open the graphical user interface of the SelectionForm, double - click on the Exit button to open its cmdExit_Click() method. Enter the codes into this method as shown in Figure 5.49 . This piece of code looks a little complicated. Let ’ s see how it works. A. First of all, we must create a new instance of the LogInForm class since we need to close all opened form windows if they are still open before we can exit this project. The point to be noted is that this instance is not one we created and applied in our LogInForm window, but it is a new instance and has no relationship with the one we used before in the LogInForm. namespace SelectWizard { public partial class SelectionForm : Form { FacultyForm facultyForm = new FacultyForm(); CourseForm courseForm = new CourseForm(); StudentForm studentForm = new StudentForm(); public SelectionForm() { InitializeComponent(); this.ComboSelection.Items.Add("Faculty Information"); this.ComboSelection.Items.Add("Course Information"); this.ComboSelection.Items.Add("Student Information"); this.ComboSelection.SelectedIndex = 0; } } } A B SelectWizard.SelectionForm SelectionForm Figure 5.47 Coding for the Selection Form. private void cmdOK_Click(object sender, EventArgs e) { if (this.ComboSelection.Text == "Faculty Information") facultyForm.Show(); else if (this.ComboSelection.Text == "Course Information") courseForm.Show(); else if (this.ComboSelection.Text == "Student Information") studentForm.Show(); else MessageBox.Show("Invalid Selection!"); } A B C D SelectWizard.SelectionForm CmdOK_Click() Figure 5.48 Coding for the OK button Click method. c05.indd 281c05.indd 281 2/11/2010 2:58:12 PM2/11/2010 2:58:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 282 Chapter 5 Data Selection Query withVisual C#.NET B. In order to access and use our original LogInForm object, we need to call the getLogIn- Form() method we built in the LogInForm class in the last section, and assign this returned object to our new instance. In this way, we make our new created instance of the LogInForm have the same reference as the original instance of the LogInForm had. Now we can use this instance to access any method attached to the original LogInForm object. C. To close the LogInForm window, the Close() method is called. D. Similarly, the Close() methods attached to other classes, such as FacultyForm, CourseForm, and StudentForm, are executed to close the associated form object. The point is that you do not need to create any new instance for each of those classes since those instances are created in this SelectionForm as the class variables or called fi elds in Visual C# 2008. E. Finally the system method Exit() is called to terminate the whole project. Suppose the user selected the fi rst information — Faculty Information. A Faculty form window will be displayed, and it is supposed to be connected to a Faculty data table in the database. If the user selected a faculty name from the ComboBox control and clicked the Select button on that form (refer to Figure 5.21 ), all information related to that faculty should be displayed on that form, exactly on fi ve labels and a picturebox. Now let ’ s fi rst see how to perform the data binding to bind controls on the Faculty form to the associated columns in the database. private void cmdExit_Click(object sender, EventArgs e) { LogInForm logForm = new LogInForm(); logForm = logForm.getLogInForm(); logForm.Close(); courseForm.Close(); facultyForm.Close(); studentForm.Close(); Application.Exit(); } SelectWizard.SelectionForm cmdExit.Click() A B C D E Figure 5.49 Coding for the Exit button Click method. One of important issues in Object - Oriented Programming is how to access an instance of a class, which has been previously created and used by some other fi les or classes, by any other class or object. A good solution is to set up a common reference or point inside the class that will be instanced and used in multiple times later in the project. A retrieving or get method is created in that class, too. By using this get method, any other class or object can access this instance. 5.11 BIND DATA TO ASSOCIATED CONTROLS IN FACULTY FORM Open the Faculty form window from the Solution Explorer window and perform the following data bindings: c05.indd 282c05.indd 282 2/11/2010 2:58:12 PM2/11/2010 2:58:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... obtained without any problems This is very interesting, is not it? Yes! This is the power provided by Visual Studio 2008 By using these Design Tools and Wizards, it is very easy to develop a professional database programming in the Visual C# 2008 environment, and it is fun to develop a database programming in the template of Windows applications 5.16 Build a Sample Database Project—SelectWizardOracle with. .. for a new sample project, SelectWizardOracle, with the Oracle Database 10g XE as the data source 5.16.1 Create a New Visual C# Project—SelectWizardOracle Now let’s create a new Visual C# project and connect it with the Oracle database we built in Chapter 2 Open Visual Studio 2008 and go to the File|New|Project menu item to open the New Project dialog Select Visual C#|Windows from the Project types pane... do with these tools and wizards This means that we create these ADO.NET objects by directly writing Visual C# code without the aid of Visual Studio design-time tools and wizards as well as the autogenerated codes All datadriven objects are created and implemented during the period the project runs In other words, all these objects are created dynamically 304 Chapter 5 Data Selection Query with Visual. .. classes of the ADO.NET in Chapter 3 To connect and implement a databasewith your Visual C# project, you need to follow the operational sequences listed next: 1 Create a new Connection String with correct parameters 2 Create a new Connection object by using the suitable Connection String built in step 1 3 Call the Open() method to open the database connection using the Try…Catch block 4 Create a new... to Microsoft Access 2007 Database 307 Now let’s first develop a sample project to access the data using the runtime objects for Microsoft Access 2007 database 5.18 QUERY DATA USING RUNTIME OBJECTS TO MICROSOFT ACCESS 2007 DATABASE The Microsoft Access 2007 database file used in this sample project is CSE_DEPT.accdb that we developed in Chapter 2, and it is located in the folder Database\ Access at the accompanying... DBProjects\Chapter 5 5.16 BUILD A SAMPLE DATABASE PROJECT— SELECTWIZARDORACLE WITH ORACLE DATABASE Basically, there is no significant difference between building a C# project with SQL Server database and another C# project with Oracle database using the Design Tools and Wizards There is a small difference when creating and connecting to the different data sources used in the applications All other elements,... facultyTableAdapter is executed to load data from the Faculty table in the database into the Faculty table in our DataSet This step is necessary since the LINQ technique is applied with the DataSet, and the DataSet must contain the valid data in all tables before this technique can be implemented 288 Chapter 5 Data Selection Query withVisual C#.NET SelectWizard.FacultyForm A B C D LINQtoDataSet() private... Oracle database Click on the Change button for the Data Source box to open the Change Data Source dialog, and then select Oracle Database as our new data source Click on the OK button to return to the Add Connection dialog Enter the following items into the associated boxes for our Oracle database: • Server name • User name • Password XE CSE_DEPT reback Recall that in Chapter 2, we built an Oracle database. .. in the Course table in the DataSet Recall that there are multiple course_id with the same faculty_id in this Course table when we built our sample database in Chapter 2 Those multiple records with the same faculty_id are distinguished by the different courses taught by that faculty To bind a ListBox to those multiple records with the same faculty_id, we cannot continue to use the binding method we used... System.Data.OleDb, System.Data.SqlClient, System.Data.Odbc, and System.Data.OracleClient As shown in Figure 5.69, four kinds of data providers are popularly used in databaseprogramming in Visual C# 2008 You must create the correct connection object based on your real database by using the specific prefix However, two components in the ADO.NET are Data Provider independent, that is, DataSet and DataTable These two components . www.verypdf.com to remove this watermark. 274 Chapter 5 Data Selection Query with Visual C#. NET As we discussed in Section 5.5.1 , these new created design tools,. www.verypdf.com to remove this watermark. 276 Chapter 5 Data Selection Query with Visual C#. NET is included in this method, and both username and password textboxes