How to use ADO.NET to write your own data access code

Slides:



Advertisements
Similar presentations
17. Data Access ADO.Net Architecture New Features of ADO.NET
Advertisements

ADO.NET: Working in Disconnected Environment Sergey Baidachni MCT, MCSD, MCDBA.
Chapter 10 ADO. What is ADO? ADO is a Microsoft technology ADO stands for ActiveX Data Objects ADO is a programming interface to access data in a database.
Coding ADO.NET Objects: Connection, Command, DataReader.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Concepts of Database Management Sixth Edition
In C# program Before you can start using the ODBC class definitions, you will need to include the right module. using System.Data.Odbc; // ODBC definitions.
CHAPTER 9 DATABASE MANAGEMENT © Prepared By: Razif Razali.
Chapter 9 Using the SqlDataSource Control. References aspx.
Chapter 11 Introduction to Database Processing. Class 11: Database Processing Use a Visual Studio Wizard to establish a database connection used to load.
Programming with Visual Basic.NET An Object-Oriented Approach  Chapter 8 Introduction to Database Processing.
11 Updating a Database Table Textbook Chapter 14.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
Neal Stublen Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
.NET Data Access and Manipulation ADO.NET. Overview What is ADO.NET? Disconnected vs. connected data access models ADO.NET Architecture ADO.NET Core Objects.
MySQL Connection using ADO.Net Connecting to MySQL from.NET Languages.
1 Introduction to ADO.NET Microsoft ADO.NET 2.0 Step by Step Rebecca M Riordan Microsoft Press, 2006.
Concepts of Database Management Seventh Edition
11 Using ADO.NET II Textbook Chapter Getting Started Last class we started a simple example of using ADO.NET operations to access the Addresses.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
ASP.NET Rina Zviel-Girshin Lecture 5
Neal Stublen Tonight’s Agenda  Database Errors  Parameterized queries  ToolStrip control  Master-detail relationships  Custom.
Module 3: Performing Connected Database Operations.
ADO.NET Objects – Data Providers Dr. Ron Eaglin. Requirements Visual Studio 2005 Microsoft SQL Server 2000 or 2005 –Adventure Works Database Installed.
1 11/10/05CS360 Windows Programming ADO.NET. 2 11/10/05CS360 Windows Programming ADO.NET  Behind every great application is a database manager o Amazon.
1 Avoiding Hacker Attacks. 2 Objectives You will be able to Avoid certain hacker attacks and crashes due to bad inputs from users.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
HNDIT Rapid Application Development
Coding ADO.NET Objects: Connection, Command, DataReader.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
Active Data Objects Using.Net ADO.Net Farooq Ahmed Amna Umber Summayya Shehzad.
DataGridView. Displaying data in a tabular format is a task you are likely to perform frequently. The DataGridView control is designed to be a complete.
1 Low Level ADO.NET Operations II Microsoft Visual C# 2008 Step by Step Chapter 25.
Introduction to Database C# MySQL onnect-C-to-MySQL 1.
.NET Data Access and Manipulation
Coding ADO.NET Objects: Connection, Command, DataReader.
C# MySQL onnect-C-to-MySQL 1.
 ADO.NET is an object-oriented set of libraries that allows you to interact with data sources  Commonly, the data source is a database, but it could.
Based on Murach (ch 17) and Deitel Slides 1. o Knowledge o Describe the hardware components of a typical multi-user system. o Describe the software components.
Common SQL keywords. Building and using CASE Tools Data Base with Microsoft SQL-Server and C#
ASP.NET Programming with C# and SQL Server First Edition
Introduction to ADO.NET
Introduction to Database Processing with ADO.NET
ADO.NET Fundamentals.
Introduction to Database Processing with ADO.NET
Unit 9.1 Learning Objectives Data Access in Code
ADO.NET and Stored Procedures
ADO.NET Framework.
PROG Advanced Web Apps 5/23/2018 Notes on ADO.NET (1) Wendi Jollymore, ACES.
How to Create Login Form using vb.net and SqlServer Database
Lecture 6 VB.Net SQL Server.
Active Data Objects Binding ASP.NET Controls to Data
Databases Intro (from Deitel)
How to use ADO.NET to write your own data access code
Unit 9.2 Database access from code Database Cycle Review
SQL commands from C# and ASP.net
VB.NET Using Database.
CIS16 Application Programming with Visual Basic
MySQL Connection using ADO.Net
How to work with bound controls and parameterized queries
Chapter 10 ADO.
How to organize and document your classes
An introduction to database programming
Coding ADO.NET Objects: Connection, Command, DataReader
PROG Advanced Web Apps 4/13/2019 Programming Data Pages Wendi Jollymore, ACES.
Active Data Objects Binding ASP.NET Controls to Data
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
ADO.NET Fundamentals.
Introduction to ADO.Net and Visual Studio Database Tools.
Presentation transcript:

How to use ADO.NET to write your own data access code Based on Murach C# 2015 Chapter 20

Objectives Applied Use a connection to access a SQL Server database. Use a data reader to retrieve data from a database. Use data commands to execute action queries or queries that return a scalar value. Use parameters to limit the data that’s processed by a data command. Knowledge Describe the use of parameters with SQL statements. Describe the use of a data reader. Describe the use of the two types of queries that don’t return result sets.

Basic ActiveX Data Object (ADO.NET ) components (ch 17) L I C T O N Data used by apps MS SQL Oracle DB2 Excel …

Different Presentation (ch 17) From http://www.siue.edu/ ~dbock/cmis142/WebNotes/Ch10Notes/10-databases_files/image006.jpg From https://i.ytimg.com/vi/ifvxhQy13u8/maxresdefault.jpg

Now: Using Commands

Connections, Commands, DataReaders The canonical usage pattern for executing database commands in ADO.Net: Step1. Create a connection object encapsulating a connection string Step 2. Open the connection by calling Open on the connection object Step 3. Create a command object encapsulating both 1. an SQL command 2. and the connection that the command will use Step. 4. Call a method on the command object to execute the command Step. 5. Close the connection by calling Close on the connection object

SqlConnection You can set the ConnectionString property after you create a connection or as you create it by passing the string to the constructor of the connection class. The values you specify for the ConnectionString property depend on the type of database you’re connecting to.

Three connection strings for the SQL Server provider For a SQL Server Express LocalDB database Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Databases\\MMABooks.mdf; Integrated Security=True When included in project Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MMABooks.mdf; A connection string for a SQL Server Express database Data Source=localhost\\SqlExpress;Initial Catalog=MMABooks;Integrated Security=True A connection string for the Jet OLE DB provider Provider=Microsoft.Jet.OLEDB.4.0;DataSource=C:\\Databases\\MMABooks.mdb

Code that creates, opens, and closes a SQL connection string connectionString = "Data Source=localhost\\SqlExpress;" + "Initial Catalog=MMABooks;Integrated Security=True"; SqlConnection connection = new SqlConnection(connectionString); connection.Open(); … //Do all your the work here connection.Close();

Three constructors for the SqlCommand class new SqlCommand() new SqlCommand(commandText) new SqlCommand(commandText, connection)

Code that creates a SqlCommand object that executes a Select statement SqlConnection connection = new SqlConnection(connectionString); string selectStatement = "SELECT CustomerID, Name, Address, City, State, ZipCode " + "FROM Customers"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection);

CommandText The CommandText and Connection properties are set to the values you pass to the constructor of the command Class. If you don’t pass these values to the constructor, you must set the CommandText and Connection properties after you create the command object. If you set the CommandText property to the name of a stored procedure, you must set the CommandType property to StoredProcedure.

SQL Parameters. Why? // Bad Idea SqlCommand cmd = new SqlCommand("select * from Customers where city = '" + inputCity + "'"; Anything placed into that TextBox will be put into inputCity and added to this SQL string. This situation invites a hacker to replace that string with something malicious string. In the worst case scenario, you could give full control of your computer away.

SQL Parameters. Better Way. // 1. declare command object with parameter SqlCommand cmd = new SqlCommand("select * from Customers where city = @City", con); // 2. define parameters used in command object SqlParameter param = new SqlParameter(); param.ParameterName = "@City"; //same spelling param.Value = inputCity; // 3. add new parameter to command object cmd.Parameters.Add(param); // get data stream reader = cmd.ExecuteReader(); Parameters are treated as literal values and not as executable code. Also, the parameter is checked for type and length. If the data does not conform to the type or length defined by the parameter, the SqlParameter class throws an exception.

SQL Parameters SQLParameter Class Represents a parameter to a SqlCommand and optionally its mapping to DataSet columns. This class cannot be inherited. A SQL Server Select statement that uses a parameter SELECT CustomerID, Name, Address, City, State, ZipCode FROM Customers WHERE CustomerID = @CustomerID A SQL Server Insert statement that uses parameters INSERT INTO Customers (Name, Address, City, State, ZipCode) VALUES (@Name, @Address, @City, @State, @ZipCode) An OLE DB or ODBC Select statement that uses a parameter WHERE CustomerID = ?

Parameter A parameter lets you place variable information into a SQL statement. When you use a parameter in the Where clause of a Select statement, the resulting query is often called a parameterized query because the results of the query depend on the values of the parameters. You can also use parameters in Insert or Update statements to provide the values for the database row or rows to be inserted or updated. Likewise, you can use parameters in a Delete statement to indicate which row or rows should be deleted. To use parameters, you code a SQL statement with placeholders for the parameters. Then, you create a parameter object that defines each parameter, and you add it to the Parameters collection of the command object that contains the SQL statement. The placeholder for a parameter in a SQL Server command is a variable whose name begins with an at sign (@). In most cases, you’ll give the variable the same name as the column it’s associated with. If you’re using the OLE DB or ODBC provider, you code the placeholder for a parameter as a question mark. The question mark simply indicates the position of the parameter.

Four constructors for the SqlParameter class new SqlParameter() new SqlParameter(name, value) new SqlParameter(name, type) new SqlParameter(name, type, size) docs.microsoft.com/en-us/dotnet/api/system.data.sqldbtype?view=netframework-4.7.2

Typical Code that creates a parameter SqlParameter customerIDParm = new SqlParameter(); customerIDParm.ParameterName = "@CustomerID"; customerIDParm.Value = customerID; Another way to create a parameter SqlParameter customerIDParm = new SqlParameter("@CustomerID", customerID); Simple and good example is here https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.7.2

Common Members of the Parameters Collections

Parameter Name, Value, Type, Size When you create a parameter, you can specify the parameter name along with a value, a data type, or a data type and size. If you don’t specify the appropriate values, you can set the values of the associated properties after you create the parameter. In addition to a name, you must set the value for a parameter before you can use it. However, the type and size can be inferred from the value. When you create parameters for a SQL Server command, you must give them the same names you used in the SQL statement since ADO.NET refers to them by name. Because the parameters for an OLE DB or ODBC command aren’t named in the SQL statement, the parameters can be given any name you want.

Using Parameters Collections A statement that adds a parameter to the Parameters collection selectCommand.Parameters.Add(customerIDParm); A statement that creates a parameter and adds it to the Parameters collection selectCommand.Parameters.AddWithValue( "@CustomerID", customerID); A statement that changes the value of an existing parameter selectCommand.Parameters["@CustomerID"].Value = customerID; indexer

SqlDataReader object Two ways to create a SqlDataReader object sqlCommand.ExecuteReader() sqlCommand.ExecuteReader(behavior) Common CommandBehavior enumeration members CloseConnection Default SingleRow

SqlDataReader object Select

Example of Code that uses a data reader to read a list of State objects connection.Open(); SqlDataReader reader = selectCommand.ExecuteReader( CommandBehavior.CloseConnection); List<State> states = new List<State>(); while (reader.Read()) { State s = new State(); s.StateCode = reader["StateCode"].ToString(); s.StateName = reader["StateName"].ToString(); states.Add(s); } reader.Close(); Closes connection when reader is closed

Select = Read To execute a command that contains a Select statement that returns a result set, you use the ExecuteReader method. This method executes the Select statement and creates a data reader object. Then, you can use the properties and methods of the data reader to work with the result set. When you execute the ExecuteReader method, you can use the CommandBehavior enumeration to specify a behavior. You can use these members to simplify your code or to improve the efficiency of your application. After you create a data reader, you use the Read method to retrieve the next row of data in the result set. Note that you must also execute the Read method to retrieve the first row of data. It’s not retrieved automatically when the data reader is created. To access a column from the most recently retrieved row, you can use the column name as an indexer. You can also specify a column by its position in the row by using an integer indexer. For example, since the first column in the States table is named StateCode, you can supply “StateCode” or zero as the indexer fora reader to retrieve the data for that column.

Select = Read cont. First, the connection that’s used by the SqlCommand object is opened. This command contains a Select statement that retrieves all the data from the States table. Then, the ExecuteReader method is used to retrieve that data and create a data reader that can process the state rows. Because the CloseConnection behavior is included on this method, the connection will be closed automatically when the data reader is closed. The ExecuteReader method also opens the data reader and positions it before the first row in the result set. Next, a List<> object that can hold State objects is created, and a while statement is used to loop through the rows in the result set. The condition on the while statement executes the Read method of the data reader. This works because the Read method returns a Boolean value that indicates whether the result set contains additional rows. As long as this condition is true, the program processes the row that was retrieved. In this case, the program creates a State object for each row in the States table and adds it to the List<> object. After all of the rows have been processed, the data reader is closed.

Scalar Value Commands that return a single value, called a scalar value. To do that, you use the ExecuteScalar method of the command. In the example, the command contains a Select statement that retrieves a sum of the invoice totals in the Invoices table. This type of summary value is often called an aggregate value. A scalar value can also be the value of a single column, a calculated value, or any other value that can be retrieved from the database. Since the ExecuteScalar method returns an Object type, you must cast that object to an appropriate data type to get its value. In this example, the object is cast to a decimal value. You can use the ExecuteScalar method with a Select statement that retrieves more than one value. In that case, though, the ExecuteScalar method returns only the first value and the others are discarded.

Code that creates and executes a command that returns an aggregate (blob) (Scalar) value string selectStatement = "SELECT SUM(InvoiceTotal) FROM Invoices"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); connection.Open(); decimal invoiceTotal = (decimal) selectCommand.ExecuteScalar; connection.Close();

Another example SqlCommand.ExecuteScalar Method Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. Ex.: cmd.CommandText = "SELECT COUNT(*) FROM dbo.region"; Int count = (Int32)cmd.ExecuteScalar();

Code that creates and executes a command that inserts a row Step 1. string insertStatement = "INSERT Products " + "(ProductCode, Description, UnitPrice) " + "VALUES (@ProductCode, @Description, @UnitPrice)"; Step 2. SqlCommand insertCommand = new SqlCommand(insertStatement, connection); Step 3. insertCommand.Parameters.AddWithValue("@ProductCode", product.Code); insertCommand.Parameters.AddWithValue("@Description", product.Description); insertCommand.Parameters.AddWithValue("@UnitPrice", product.Price); Step 4. try { connection.Open(); int productCount = insertCommand.ExecuteNonQuery(); } catch (SqlException ex) MessageBox.Show(ex.Message); finally { connection.Close();

Customer Maintenance: The dialog box that’s displayed to confirm a delete operation

The Customer Maintenance form (multiple forms) No ToolStrip The Add/Modify Customer form

Add, Modify, Delete Customer To add a customer, the user clicks the Add button on the Customer Maintenance form to display a blank Add Customer form. Then, the user enters the data for the new customer and clicks the Accept button to return to the Customer Maintenance form. To modify the data for an existing customer, the user enters the customer ID and clicks the Get Customer button to display the information for that customer. Then, the user clicks the Modify button to display the Modify Customer form, makes the appropriate modifications, and clicks the Accept button to return to the CustomerMaintenance form. To delete a customer, the user enters the customer ID and clicks the Get Customer button to display the information for that customer. Then, the user clicks the Delete button and responds to the dialog box that’s displayed to confirm the delete operation.

Some irrelevant classes are not shown The class diagram (In Solution Explorer or Class View, right-click the project and choose View, then choose View Class Diagram.)* Some irrelevant classes are not shown *May not be available in VS Community Edition by default

Important: The code for the CustomerDB class (GetCustomer) public static class CustomerDB { public static Customer GetCustomer(int customerID) SqlConnection connection = MMABooksDB.GetConnection(); string selectStatement = "SELECT CustomerID, Name, Address, City, State, ZipCode " + "FROM Customers " + "WHERE CustomerID = @CustomerID"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); selectCommand.Parameters.AddWithValue("@CustomerID", customerID); try connection.Open(); SqlDataReader custReader = selectCommand.ExecuteReader(CommandBehavior.SingleRow); if (custReader.Read()) Customer customer = new Customer(); customer.CustomerID = (int)custReader["CustomerID"]; customer.Name = custReader["Name"].ToString(); customer.Address = custReader["Address"].ToString(); customer.City = custReader["City"].ToString(); customer.State = custReader["State"].ToString(); customer.ZipCode = custReader["ZipCode"].ToString(); return customer; } else return null; catch (SqlException ex) throw ex; finally connection.Close();

The code for the CustomerDB class (AddCustomer) public static int AddCustomer(Customer customer) { SqlConnection connection = MMABooksDB.GetConnection(); string insertStatement = "INSERT Customers " + "(Name, Address, City, State, ZipCode) " + "VALUES (@Name, @Address, @City, @State, @ZipCode)"; SqlCommand insertCommand = new SqlCommand(insertStatement, connection); insertCommand.Parameters.AddWithValue( "@Name", customer.Name); "@Address", customer.Address); "@City", customer.City); "@State", customer.State); "@ZipCode", customer.ZipCode); try connection.Open(); insertCommand.ExecuteNonQuery(); string selectStatement = "SELECT IDENT_CURRENT('Customers') FROM Customers"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); int customerID = Convert.ToInt32(selectCommand.ExecuteScalar()); return customerID; } catch (SqlException ex) throw ex; finally connection.Close();

The code for the CustomerDB class (UpdateCustomer) public static bool UpdateCustomer(Customer oldCustomer, Customer newCustomer){ SqlConnection connection = MMABooksDB.GetConnection(); string updateStatement = "UPDATE Customers SET " + "Name = @NewName, " + "Address = @NewAddress, " + "City = @NewCity, " + "State = @NewState, " + "ZipCode = @NewZipCode " + "WHERE CustomerID = @oldCustomerID " + "AND Name = @OldName " + "AND Address = @OldAddress " + "AND City = @OldCity " + "AND State = @OldState " + "AND ZipCode = @OldZipCode"; SqlCommand updateCommand = new SqlCommand(updateStatement, connection); updateCommand.Parameters.AddWithValue("@NewName", newCustomer.Name); updateCommand.Parameters.AddWithValue("@NewAddress", newCustomer.Address); updateCommand.Parameters.AddWithValue("@NewCity", newCustomer.City); updateCommand.Parameters.AddWithValue("@NewState", newCustomer.State); updateCommand.Parameters.AddWithValue("@NewZipCode", newCustomer.ZipCode); updateCommand.Parameters.AddWithValue("@OldCustomerID", oldCustomer.CustomerID); updateCommand.Parameters.AddWithValue("@OldName", oldCustomer.Name); updateCommand.Parameters.AddWithValue("@OldAddress", oldCustomer.Address); updateCommand.Parameters.AddWithValue("@OldCity", oldCustomer.City); updateCommand.Parameters.AddWithValue("@OldState", oldCustomer.State); updateCommand.Parameters.AddWithValue("@OldZipCode", oldCustomer.ZipCode); try{ connection.Open(); int count = updateCommand.ExecuteNonQuery(); if (count > 0) return true; else return false; }catch (SqlException ex){ throw ex; } finally{ connection.Close();

The code for the CustomerDB class (DeleteCustomer) public static bool DeleteCustomer(Customer customer) { SqlConnection connection = MMABooksDB.GetConnection(); string deleteStatement = "DELETE FROM Customers " + "WHERE CustomerID = @CustomerID " + "AND Name = @Name " + "AND Address = @Address " + "AND City = @City " + "AND State = @State " + "AND ZipCode = @ZipCode"; SqlCommand deleteCommand = new SqlCommand(deleteStatement, connection); deleteCommand.Parameters.AddWithValue("@CustomerID", customer.CustomerID); deleteCommand.Parameters.AddWithValue("@Name", customer.Name); deleteCommand.Parameters.AddWithValue("@Address", customer.Address); deleteCommand.Parameters.AddWithValue("@City", customer.City); deleteCommand.Parameters.AddWithValue("@State", customer.State);"@ZipCode",customer.ZipCode); try { connection.Open(); int count = deleteCommand.ExecuteNonQuery(); if (count > 0) return true; else return false; } catch (SqlException ex) throw ex; finally connection.Close();

The code for the StateDB class public static class StateDB { public static List<State> GetStates() List<State> states = new List<State>(); SqlConnection connection = MMABooksDB.GetConnection(); string selectStatement = "SELECT StateCode, StateName " + "FROM States " + "ORDER BY StateName"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); try connection.Open(); SqlDataReader reader = selectCommand.ExecuteReader(); while (reader.Read()) State s = new State(); s.StateCode = reader["StateCode"].ToString(); s.StateName = reader["StateName"].ToString(); states.Add(s); } reader.Close(); catch (SqlException ex) throw ex; finally connection.Close(); return states;

The code for the MMABooksDB class public static class MMABooksDB { public static SqlConnection GetConnection() string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MMABooks.mdf;" + "Integrated Security=True"; SqlConnection connection = new SqlConnection(connectionString); return connection; }

The Customer Maintenance form public partial class frmCustomerMaintenance : Form { public frmCustomerMaintenance() InitializeComponent(); } private Customer customer; private void btnGetCustomer_Click(object sender, EventArgs e) if (Validator.IsPresent(txtCustomerID) && Validator.IsInt32(txtCustomerID)) int customerID = Convert.ToInt32(txtCustomerID.Text); this.GetCustomer(customerID); if (customer == null) MessageBox.Show("No customer found with this ID. " + "Please try again.", "Customer Not Found"); this.ClearControls(); else this.DisplayCustomer();

The Customer Maintenance form (cont.) private void GetCustomer(int customerID) { try customer = CustomerDB.GetCustomer(customerID); } catch (Exception ex) MessageBox.Show(ex.Message, ex.GetType().ToString()); private void ClearControls() txtCustomerID.Text = ""; txtName.Text = ""; txtAddress.Text = ""; txtCity.Text = ""; txtState.Text = ""; txtZipCode.Text = ""; btnModify.Enabled = false; btnDelete.Enabled = false; txtCustomerID.Focus();

The Customer Maintenance form (cont.) private void DisplayCustomer() { txtName.Text = customer.Name; txtAddress.Text = customer.Address; txtCity.Text = customer.City; txtState.Text = customer.State; txtZipCode.Text = customer.ZipCode; btnModify.Enabled = true; btnDelete.Enabled = true; } private void btnAdd_Click(object sender, EventArgs e) frmAddModifyCustomer addCustomerForm = new frmAddModifyCustomer(); addCustomerForm.addCustomer = true; DialogResult result = addCustomerForm.ShowDialog(); if (result == DialogResult.OK) customer = addCustomerForm.customer; txtCustomerID.Text = customer.CustomerID.ToString(); this.DisplayCustomer();

The Customer Maintenance form (cont.) private void btnModify_Click(object sender, EventArgs e) { frmAddModifyCustomer modifyCustomerForm = new frmAddModifyCustomer(); modifyCustomerForm.addCustomer = false; modifyCustomerForm.customer = customer; DialogResult result = modifyCustomerForm.ShowDialog(); if (result == DialogResult.OK) customer = modifyCustomerForm.customer; this.DisplayCustomer(); } else if (result == DialogResult.Retry) this.GetCustomer(customer.CustomerID); if (customer != null) else this.ClearControls();

The Customer Maintenance form (cont.) private void btnDelete_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Delete " + customer.Name + "?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) try if (! CustomerDB.DeleteCustomer(customer)) MessageBox.Show("Another user has updated or deleted " + "that customer.", "Database Error"); this.GetCustomer(customer.CustomerID); if (customer != null) this.DisplayCustomer(); else this.ClearControls(); } catch (Exception ex) MessageBox.Show(ex.Message, ex.GetType().ToString()); private void btnExit_Click(object sender, EventArgs e) this.Close();

The Add/Modify Customer form public partial class frmAddModifyCustomer : Form { public frmAddModifyCustomer() InitializeComponent(); } public bool addCustomer; public Customer customer; private void frmAddModifyCustomer_Load(object sender, EventArgs e) this.LoadStateComboBox(); if (addCustomer) this.Text = "Add Customer"; cboStates.SelectedIndex = -1; else this.Text = "Modify Customer"; this.DisplayCustomer();

The Add/Modify Customer form private void LoadStateComboBox() { List<State> states = new List<State>(); try states = StateDB.GetStates(); cboStates.DataSource = states; cboStates.DisplayMember = "StateName"; cboStates.ValueMember = "StateCode"; } catch (Exception ex) MessageBox.Show(ex.Message, ex.GetType().ToString()); private void DisplayCustomer() txtName.Text = customer.Name; txtAddress.Text = customer.Address; txtCity.Text = customer.City; cboStates.SelectedValue = customer.State; txtZipCode.Text = customer.ZipCode;

The Add/Modify Customer form private void btnAccept_Click(object sender, EventArgs e) { if (IsValidData()) if (addCustomer) customer = new Customer(); this.PutCustomerData(customer); try customer.CustomerID = CustomerDB.AddCustomer(customer); this.DialogResult = DialogResult.OK; } catch (Exception ex) MessageBox.Show(ex.Message, ex.GetType().ToString()); else Customer newCustomer = new Customer(); newCustomer.CustomerID = customer.CustomerID; this.PutCustomerData(newCustomer); if (! CustomerDB.UpdateCustomer(customer, newCustomer)) MessageBox.Show("Another user has updated or " + "deleted that customer.", "Database Error"); this.DialogResult = DialogResult.Retry; customer = newCustomer;

The Add/Modify Customer form private bool IsValidData() { return Validator.IsPresent(txtName) && Validator.IsPresent(txtAddress) && Validator.IsPresent(txtCity) && Validator.IsPresent(cboStates) && Validator.IsPresent(txtZipCode); } private void PutCustomerData(Customer customer) customer.Name = txtName.Text; customer.Address = txtAddress.Text; customer.City = txtCity.Text; customer.State = cboStates.SelectedValue.ToString(); customer.ZipCode = txtZipCode.Text;

The Add/Modify Customer form (cont.) private void PutCustomerData(Customer customer) { customer.Name = txtName.Text; customer.Address = txtAddress.Text; customer.City = txtCity.Text; customer.State = cboStates.SelectedValue.ToString(); customer.ZipCode = txtZipCode.Text; }

20-1 Write the code for a Product Maintenance application

Project 4-5 Register products