Beginning C# 2005 Databases From Novice to Professional phần 9 ppsx

52 309 0
Beginning C# 2005 Databases From Novice to Professional phần 9 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Table 15-1. Common ADO.NET Events Object Event Delegate Remarks SqlDataAdapter RowUpdating SqlRowUpdatingEventHandler Raised before the row is updated in the database. The event h andler receives a SqlRowUpdatingEventArgs object. SqlDataAdapter RowUpdated SqlRowUpdatedEventHandler Raised after a row is updated in the database. The event handler receives a SqlRowUpdatedEventArgs object. SqlDataAdapter FillError FillErrorEventHandler Raised when the Fill method is called. The event handler receives a FillErrorEventArgs object. DataRow ColumnChanging DataColumnChangeEventHandler Raised when the data in a data column is changing. The handler receives a DataColumnChangeEventArgs object. DataRow ColumnChanged DataColumnChangeEventHandler Raised after a value has been changed for the specified data column in a data row. The handler receives a DataColumnChangedEventArgs object. DataTable RowChanging DataRowChangeEventHandler Raised when a data row is changing. The event handler receives a DataChangeEventArgs object. DataTable RowChanged DataRowChangeEventHandler Raised after a data row has changed. The event handler receives a DataChangeEventArgs object. DataTable RowDeleting DataRowChangeEventHandler Raised before a data row is deleted. The event handler receives a DataRowChangeEventArgs object. DataTable RowDeleted DataRowChangeEventHandler R aised after a data r ow is deleted. The event handler receives a DataRowChangeEventArgs object. CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS 391 Try It Out: Using RowUpdating and RowUpdated Events Let ’ s experiment with the SQL Server data adapter’s RowUpdating and RowUpdated ev ents; in this example , you’ll see how they’re raised and handled when a value in a dataset changes: 777Xch15final.qxd 11/18/06 2:34 PM Page 391 1. Insert the code in Listing 15-5 into the click event handler for the third button. Listing 15-5. button3_Click() // clear list box listBox1.Items.Clear(); // create connection SqlConnection conn = new SqlConnection(@" data source = .\sqlexpress; integrated security = true; database = northwind "); try { // open connection conn.Open(); // create data adapter SqlDataAdapter da = new SqlDataAdapter( @" select * from Customers ", conn ); // build command SqlCommandBuilder cb = new SqlCommandBuilder(da); // create and fill dataset (select only first row) DataSet ds = new DataSet(); da.Fill(ds, 0, 1, "Customers"); // add handlers da.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating); da.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated); CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS392 777Xch15final.qxd 11/18/06 2:34 PM Page 392 // modify dataset DataTable dt = ds.Tables["Customers"]; dt.Rows[0][1] = "The Volcano Corporation"; // update - this operation fires two events (RowUpdating/RowUpdated) da.Update(ds, "Customers"); // remove handlers da.RowUpdating -= new SqlRowUpdatingEventHandler(OnRowUpdating); da.RowUpdated -= new SqlRowUpdatedEventHandler(OnRowUpdated); } catch (SqlException ex) { MessageBox.Show(ex.Message); } finally { // close connection conn.Close(); } 2. Add the method in Listing 15-6 to class Form1 to handle the RowUpdating event. Listing 15-6. Handling the RowUpdating Event private void OnRowUpdating(object sender, SqlRowUpdatingEventArgs e) { DisplayEventArgs(e); } 3. Add the method in Listing 15-7 to class Form1 to handle the RowUpdated event. Listing 15-7. H andling the RowUpdated E v ent private void OnRowUpdated(object sender, SqlRowUpdatedEventArgs e) { DisplayEventArgs(e); } 4. Add the overloaded DisplayEventArgs methods in Listing 15-8 to class Form1. CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS 393 777Xch15final.qxd 11/18/06 2:34 PM Page 393 Listing 15-8. Displaying Event Arguments private void DisplayEventArgs(SqlRowUpdatingEventArgs args) { listBox1.Items.Add("OnRowUpdating event"); if (args.Status != UpdateStatus.Continue) listBox1.Items.Add("RowStatus = " + args.Status.ToString()); } private void DisplayEventArgs(SqlRowUpdatedEventArgs args) { listBox1.Items.Add("OnRowUpdated event"); listBox1.Items.Add("Records Affected = " + args.RecordsAffected); } 5. Build and run the solution with Ctrl+F5. Click the SqlDataAdapter RowUpdating Event button. You’ll see the results shown in Figure 15-4. 6. Click the button again. Y ou ’ ll see the results shown in Figure 15-5. CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS394 Figure 15-4. Displaying RowUpdating and RowUpdated Event information 777Xch15final.qxd 11/18/06 2:34 PM Page 394 How It Works Note that the first time the button is clicked, the RowUpdating and RowUpdated events fire. But the second time, the RowUpdated event doesn’t fire, and the RowStatus is SkipCurrentRow. What you’ve essentially done in this example is retrieve one row from the Customers table, update it to get the RowUpdating and RowUpdated events to fire, and handle the events. You create and initialize a data adapter and a command builder: // create data adapter SqlDataAdapter da = new SqlDataAdapter( @" select * from Customers ", conn ); // build command SqlCommandBuilder cb = new SqlCommandBuilder(da); Then you create a dataset and use the Fill method to fill it with one row of data: CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS 395 Figure 15-5. Displaying only RowUpdating Event information 777Xch15final.qxd 11/18/06 2:34 PM Page 395 // create and fill dataset (select only first row) DataSet ds = new DataSet(); da.Fill(ds, 0, 1, "Customers"); Then you add handlers for the RowUpdating and RowUpdated events using the += operator: // add handlers da.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating); da.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated); You then modify the dataset. You change the name of the company to “The Volcano Corporation”: // modify dataset DataTable dt = ds.Tables["Customers"]; dt.Rows[0][1] = "The Volcano Corporation"; You then update the database by sending the dataset changes to it. At that moment, the RowUpdating event and the RowUpdated event fire: // update - this operation fires two events (RowUpdating/RowUpdated) da.Update(ds, "Customers"); Finally, you remove the handlers. It isn’t necessary in this example, but we’ve shown it for demonstration purposes . As mentioned earlier in the chapter, the location in code where handlers are added and removed is important and will affect whether events are handled, even if event handlers are present. Notice that you use the -= operator to remove the handlers: // remove handlers da.RowUpdating -= new SqlRowUpdatingEventHandler(OnRowUpdating); da.RowUpdated -= new SqlRowUpdatedEventHandler(OnRowUpdated); B oth the OnRowUpdating and OnRowUpdated ev ent handlers call a method named DisplayEventArgs. The OnRowUpdating ev ent handler r eceiv es the SqlRowUpdatingEventArgs object, and the OnRowUpdated ev ent handler r eceiv es the SqlRowUpdatedEventArgs object. As these two ev ents ar e differ ent, the delegates of these ev ents pass slightly differ ent infor mation to the handler : CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS396 777Xch15final.qxd 11/18/06 2:34 PM Page 396 private void OnRowUpdating(object sender, SqlRowUpdatingEventArgs e) { DisplayEventArgs(e); } private void OnRowUpdated(object sender, SqlRowUpdatedEventArgs e) { DisplayEventArgs(e); } The overloaded DisplayEventArgs method adds an item to the list box to indicate that the executing code has entered it. It also uses the argument passed to it and checks Status. Status is an enumeration of type UpdateStatus. If Status isn’t UpdateStatus. Continue, the status is written to the list box. When a row is in the process of being updated, if a change has been made to the row, the status of the row will be marked as Continue and the RowUpdated event will fire for the row. If the status isn’t UpdateStatus. Continue, then the RowUpdated event won’t fire: private void DisplayEventArgs(SqlRowUpdatingEventArgs args) { listBox1.Items.Add("OnRowUpdating event"); if (args.Status != UpdateStatus.Continue) listBox1.Items.Add("RowStatus = " + args.Status.ToString()); } If the row can be updated, the RowUpdated event will fire, which will be handled by the OnRowUpdated event handler, which in turn will pass the execution to the version of the DisplayEventArgs method that takes the SqlRowUpdatedEventArgs object as the parameter. This object carries with it information about how many rows were updated in the RecordsAffected property, which is displayed in the list box: private void DisplayEventArgs(SqlRowUpdatedEventArgs args) { listBox1.Items.Add("OnRowUpdated event"); listBox1.Items.Add("Records Affected = " + args.RecordsAffected); } The first time the button is clicked, the company name changes to “The Volcano Corporation.” This raises both the RowUpdating and the RowUpdated events. The second time the button is clicked, since the company name is already “The Volcano Corpora- tion,” only the RowUpdating event is raised, and the row’s UpdateStatus is marked as SkipCurrentRow. So the RowUpdated event doesn’t fire. CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS 397 777Xch15final.qxd 11/18/06 2:34 PM Page 397 Working with Multiple Handlers It’s also possible to have the same event call multiple handlers. You can do this in two ways. You can individually bind the event to two different event handlers, or you can use a multicast delegate, where you specify a list of event handlers, and, when the event is fired, all the listed handlers will be invoked successively. You’ll use the first alterna- tive in the following example. Try It Out: Using Multiple Handlers for the Same Event Follow these steps: 1. Insert the code in Listing 15-9 into the click event handler for the fourth button. Listing 15-9. button4_Click() // create connection SqlConnection conn = new SqlConnection(@" data source = .\sqlexpress; integrated security = true; database = northwind "); // delegate the StateChange event to two handlers conn.StateChange += new StateChangeEventHandler(ConnStateChange); conn.StateChange += new StateChangeEventHandler(ConnStateChange2); // create command SqlCommand cmd = new SqlCommand(); cmd.CommandText = "SELECT TOP 1 CustomerId, CompanyName FROM Customers"; cmd.Connection = conn; try { listBox1.Items.Clear(); // open connection conn.Open(); // create data reader SqlDataReader dr = cmd.ExecuteReader(); while(dr.Read()) CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS398 777Xch15final.qxd 11/18/06 2:34 PM Page 398 { listBox1.Items.Add(dr.GetString(0) + "-" + dr.GetString(1)); } } catch(SqlException ex) { MessageBox.Show (ex.Message); } finally { // close connection conn.Close(); } 2. Add the code in Listing 15-10 to class Form1 as a second event handler for the StateChange event. Listing 15-10. Alternate Handler for the StateChange Event private void ConnStateChange2(object sender, StateChangeEventArgs ev) { listBox1.Items.Add(" "); listBox1.Items.Add("Entering Second StateChange EventHandler"); listBox1.Items.Add("Sender = " + sender.ToString()); listBox1.Items.Add("Original State = " + ev.OriginalState.ToString()); listBox1.Items.Add("Current State = " + ev.CurrentState.ToString()); listBox1.Items.Add("Exiting Second StateChange EventHandler"); listBox1.Items.Add(" "); } 3. Build and run the solution with Ctrl+F5. Click the Multiple Handlers button. You’ll see the r esults shown in Figure 15-6. Observe that the event log in Figure 15-6 shows that the first StateChange event han- dler was invoked and then the second StateChange event handler was invoked. You can code these two handlers to perform different actions, of course. CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS 399 777Xch15final.qxd 11/18/06 2:34 PM Page 399 How It Works You separately bind the StateChange event to two different handlers: // delegate the StateChange event to two handlers conn.StateChange += new StateChangeEventHandler(ConnStateChange); conn.StateChange += new StateChangeEventHandler(ConnStateChange2); Notice that in the second instance, you bind it to the CnStateChange2 method, which is the same as CnStateChange except for its enter and exit messages: private void ConnStateChange2(object sender, StateChangeEventArgs ev) { listBox1.Items.Add(" "); listBox1.Items.Add("Entering Second StateChange EventHandler"); listBox1.Items.Add("Sender = " + sender.ToString()); listBox1.Items.Add("Original State = " + ev.OriginalState.ToString()); listBox1.Items.Add("Current State = " + ev.CurrentState.ToString()); listBox1.Items.Add("Exiting Second StateChange EventHandler"); listBox1.Items.Add(" "); } CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS400 Figure 15-6. Multiple state change event handlers 777Xch15final.qxd 11/18/06 2:34 PM Page 400 [...]... bind any number of events to their respective event handlers from within the same function • How to use a data adapter’s RowUpdating and RowUpdated events to determine the status of a row before and after it’s updated • How to bind the same event to more than one event handler This results in each event handler being called and executed In the next chapter, you’ll see how to store and retrieve binary... must cycle (stop and restart) SSE before rerunning the program, to remove the table by re-creating an empty tempdb database You’ll see how to avoid this problem in “Working with Text Data” later in this chapter Retrieving Images from a Database Now that you’ve stored some images, let’s retrieve and display them with a Windows application Try It Out: Displaying Stored Images To display your stored images:... retrieve the text you just stored Retrieving Data from Text Columns Retrieving data from TEXT columns is just like retrieving it from the smaller character data types You’ll now write a simple console program to see how this works Try It Out: Retrieving Text Data Follow these steps: 1 Add a C# Console Application project named RetrieveText to the solution 2 Rename Program.cs to RetrieveText.cs, and replace... Summary In this chapter, we covered the basics of handling ADO.NET events You saw what events are and how to use delegates to bind them to event handlers Specifically, you saw the following: • That a connection’s StateChange event fires when the state changes from Open to Closed or from Closed to Open You wrote an event handler for this event using the StateChangeEventHandler delegate In the process,... is debatable Needless to say, it has always implied a data type that can handle large amounts of (amorphous) data, and SQL Server documentation uses BLOB as a generic term for large data and data types Storing Images in a Database Let’s start by creating a database table for storing images and then loading some images into it We’ll use small images but use VARBINARY(MAX) to store them We’ll use images... things You called an instance method to create a table to hold images: // Create table loader.CreateImageTable(); You called an instance method to prepare a command (yes, you finally prepared a command, since you expected to run it multiple times) to insert images: // Prepare insert loader.PrepareInsertImages(); You then looped through the image files and inserted them: 4 09 777Xch16final.qxd 410 11/18/06... text and binary data, including the following: • What data types to use • Loading, retrieving, and displaying image data • Working with headers in binary data • Working with data too large to fit easily into memory • Retrieving and storing text data We’ll also present the T-SQL for creating a table in the tempdb database, which is intended to hold any temporary table We’ll start by covering what data... Application project named DisplayImages to your solution Rename Form1.cs to DisplayImages.cs 2 Add a text box, a button, and a picture box control to the form and set its Text property to Display Images as in Figure 16-2 777Xch16final.qxd 11/18/06 2:33 PM Page 413 CHAPTER 16 s WORKING WITH TEXT AND BINARY DATA Figure 16-2 DisplayImages form 3 Add a new class named Images to the project Replace the code in... in the bold code shown here) of type Images into DisplayImagesDesigner.cs: private private private private System.Windows.Forms.TextBox textBox1; System.Windows.Forms.Button button1; System.Windows.Forms.PictureBox pictureBox1; Images images; 5 Insert the code in Listing 16-3 into DisplayImages.cs after the call to InitializeComponent() in the constructor 415 777Xch16final.qxd 416 11/18/06 2:33 PM... Works You declared a type, Images, to access the database and provide methods for the form components to easily get and display images In its constructor, you connected to the database and created a data reader to handle the result set of a query that retrieves all the images you stored earlier // Constructor public Images() { imageConnection = new SqlConnection(@" data source = \sqlexpress; integrated . to use delegates to bind them to event handlers. Specifically, you saw the following: • That a connection’s StateChange event fires when the state changes from Open to Closed or from Closed to. handlers to perform different actions, of course. CHAPTER 15 ■ WORKING WITH ADO.NET EVENTS 399 777Xch15final.qxd 11/18/06 2:34 PM Page 399 How It Works You separately bind the StateChange event to. Event Follow these steps: 1. Insert the code in Listing 15 -9 into the click event handler for the fourth button. Listing 15 -9. button4_Click() // create connection SqlConnection conn = new SqlConnection(@" data

Ngày đăng: 09/08/2014, 14:20

Từ khóa liên quan

Mục lục

  • Beginning C# 2005 Databases: From Novice to Professional

    • Chapter 16 Working with Text and Binary Data

    • Chapter 17 Using XML.

Tài liệu cùng người dùng

Tài liệu liên quan