Listing A3 DataBound GridView Sample

lt Page Language C AutoEventWreup-'true CodeFile-'Default.aspx.cs lnherits _Default gt lt DOCTYPE html PUBLIC - W3C DTD XHTML 1.1 EN http www.w3.org TR xhtml11 DTD xhtml 11 ,dtd gt lt html gt lt head runat server gt lt title gt Untitled Page lt title gt lt head gt lt body gt lt form id form1 runat server gt lt div gt lt asp GridView ID GridView1 runat-'server AutoGenerateColumns-'False DataKeyNames-'CustomerlD DataSourcelD SqlDataSource1 EmptyDataText-'There are no data records to display. gt...

Index Ptf

SYMBOLi A i C Q i E rn t l ID y Ml CsU E El Ml EJ y Bfl W Val property, virtual mode Validate method ValidateChildren method using AutoValidate property validation down control hierarchy validation up control hierarchy Validated events DataGridView defined overview of setting error provider message in response to Validation calling EndEdit and capturing data errors on data sets data concurrency resolution DataGridView DataError event DataGridView error displays DataGridView events down control...

Listing 36 Connecting Data Sources to Controls with a BindingSource

private void On Form Load object sender, EventArgs e Set up event handlers for connector position changed and text box text changed events OnPositionChanged m_PositionTextBox.TextChanged OnPositionTextChanged Set up data bindings CustomersDataSet nwData CustomersDataSet.GetCustomersQ m_CustomersGrid.DataSource m_CustomersBindingSource m_CustomersBindingSource.DataSource nwData.Customers AddTextBoxDataBindings AddComboBoxDataBindingsQ private void AddTextBoxDataBindings m_CustomersBindingSource,...

Conventions

Developing applications is more about tools and less about code. However, there is a lot of code in this book, and I have adopted some common conventions to help make things easier. References to classes, variables, namespaces, and other artifacts that manifest themselves in code are in a monospace font this helps you distinguish an instance of theDataSet class from a conceptual discussion of data sets. Short code listings are presented inline within the text using a different monospace font...

Figure 47 Currency Exchange Data Set

The user interface shown in Figure 4.6 lets users browse through the records of exchange rate data, with the related country information for each exchange rate included in the formas if it were all stored as a single table of data. However, the normalized format of the data in the data set reguires some additional work to provide this appearance to the user. To support this display, each exchange rate record needs to retrieve two corresponding country records to display their data in place with...

DateTimePicker Controls

The DateTimePicker is a fairly complex control that allows the display and editing of formatted date and time information. It looks like a ComboBoxwith the date and time information displayed in text form within it. The formatting of that display can be set based on a number of predefined formats or by using a custom formatting string. When the drop-down arrow is selected, a calendar control appears, allowing an intuitive and rich date selection mechanism. The ValueChanged event is the default...

Listing 81 DataGridView OnCellFormatting Method Override

protected override void OnCellFormatting DataGridViewCellFormattingEventArgs args Call home to base base.OnCellFormatting args First row always displays if args.Rowlndex 0 return args.Value string.Empty args.FormattingApplied true private bool lsRepeatedCellValue int rowlndex, int collndex Rows rowlndex ,Cells collndex DataGridViewCell prevCell Rows rowlndex - 1 .Cells collndex if currCell.Value prevCell.Value currCell.Value null amp amp prevCell.Value null amp amp currCell.Value.ToString...

Table D5 XPathNavigator Query Methods

Takes an XPath expression as a string or a compiled XPath Expression object and returns an XPathNodelterator containing the nodes that matched the query. Takes a precompiled XPathExpression object and executes the query, returning an XPathNodelterator containing the nodes that matched the query. Lets you select all child nodes of the current node with a particular node type or all child elements of a given name. This only selects matching nodes that are one level under the current node in the...

Table D6 XPathNavigator Navigation Methods

Takes an XPathNavigator as a parameter and moves the current position of the navigator it is called on to the same node as the navigator that is passed as the parameter. You can achieve a similar result by calling the Clone method on an existing navigator to obtain a new navigator object positioned on the same node within the document. Moves to the next sibling node at the same level in the hierarchy. Does not apply to attributes or namespace nodes. Moves to the previous sibling node at the...

DataGridViewComboBoxColumn

This column type contains cells of type DataGridViewComboBoxCell, which renders itself like a standardComboBox control within the cell. This column type is definitely the most complex built-in column type for the DataGridView, and it exposes a number of properties that drive its behavior, as described in Table 6.4. Table 6.4. DataGridViewComboBoxColumn Properties Table 6.4. DataGridViewComboBoxColumn Properties True if AutoComplete functionality is enabled when the cell is in edit mode, false...

Figure 519 Formatting and Advanced Binding Dialog

End -the properties of a tontnrf to a soxtc., and f orroiit t he fesult. Specify the foirmat fc date and time values. Format type ftata Source Update Mode CfiVjiftiftn Monday, Octobcr 03, 2D05 lt to05 AM EOftt OOS tG AM 10 3 2005 9 46-05 AM

Creating a Custom Collection Type Based on BindingList

Say you want to create a strongly typed collection of Customer objects that support searching and sorting, and that you want to take over the construction process of instances of Customers that get added to the collection through data-binding mechanisms. The first step in this process is to declare a class derived fromBindingList lt T gt with the appropriate type parameter public class CustomerCollection BindingList lt Customer gt Taking Over the Construction Process For a next step, let's take...

DataBinding Expressions

To include an expression in your markup code that is evaluated when data binding occurs, you have enclosed it in the special lt gt syntax. The code that you enclose in these data-binding expressions can include code that gets evaluated directly, as if it were in the code-behind, such as referencing a property or method on the code-behind class as discussed earlier. lt asp TextBox ID TextBox3 runat-'server Text lt SomeProperty gt gt lt asp TextBox gt lt asp TextBox ID TextBox2 runat-'server Text...

The ICancelAddNew Interface Supporting Transactional Inserts in a Collection

The ICancelAddNew interface lets you add and edit new items to a collection with the item in a transient state, which allows you to remove the new item before finalizing the addition if desired if a problem occurs while initializing the object's properties . This interface was added in .NET 2.0 to break an implicit coupling that occurs with the lEditableObject interface when adding new items to a collection. Prior to adding this interface, objects in the collection that implemented the...

Supporting Searching with IBindingList

The final category of functionality described by the IBindingList interface is searching. To search effectively, you usually need to apply some sort of indexing over the collection. The SupportsSearching property indicates whether a collection even supports searching. If it returns true, then you should be able to safely call theFind method with a property descriptor for the property you want to match against and an object reference that contains the value to match with. If you are implementing...

Update Databinding With Rtf

SYMBOLi A i C Q i E G t l ID y Ml CsU E El Ml EJ S LUIY W X Fat client See Smart client applicationsl Fault tolerance Fields Fill method filling typed data sets with table adapters loading data sets from database untyped data sets Update method vs Fill. AutoSizeMode FillError event, SglDataAdapter FillWeight property, AutoSizeMode FillWeight property, DataGridViewColumn Filter property IBindingListView 2nd setting on binding source synchronizing many-to-many relationships Filtered grid control...

Connection Management

The table adapters that the designer generates contain code to initialize the connection to the database. By default, when you drag a table onto the data set designer surface from Server Explorer, an app.config configuration file is added to your project. The connection string to the database you are working with is added to the connectionStrings configuration section in that configuration file lt add NorthwindConnectionString connectionString-'Data Source localhost lnitial Catalog Northwind...

DataGridView Validation Events

The DataGridView control is a Windows Forms control derived from theControl base class, and it is a complex data container. The DataGridView control lets you handle validation at several levels. The grid itself is a control, and thus raise alidating and Validated events when the focus shifts away from the grid. However, usually you will want to handle validating a little closer to the data that is being validated, either at the individual row or cell level. To allow this, the DataGridView fires...

Behind the Scenes Designer Code and Data Sources Files

Understanding what is going on behind the scenes is always important, especially when the designer-generated code isn't doing exactly what you want. The first thing to understand is that all of the controls and components generated by the designer actions, along with the supporting code to set up data-binding objects and properties, are part of the standard Windows Forms designer-generated code. With Visual Studio 2005, this code is now placed in a separate code file using partial classes, and...

Figure 86 Filter Textbox Autocomplete

r'artii p H.-irr- g- n.31-3 lln- i To get this kind of scenario working correctly requires a good understanding of binding sources and grids, as well as control and data-binding lifecycles. You also need to understand other Windows Forms concepts like working with ComboBox controls and using autocomplete functionality on a text box. I'll step through all of this in the following sections. If you want to follow along to create a control like this, you need to create a Windows Control Library...

Supporting Object Edit Notifications with Property Change Events

Another problem people frequently encounter when first trying to use collections of objects as their data source is detecting changes in the bound data objects if those changes aren't made directly through the bound control getting or setting properties on the object. When you change an object property by editing it through a bound control, the control will change the values through the property descriptors for the object. Containers for those objects, such as the binding source, can hook up a...

Generating Bound Controls with the Visual Studio Designer

BY NOW, YOU are hopefully getting a firm grasp on the code involved for setting up data binding between controls and data sources using BindingSource components orBinding objects as middlemen. However, writing all that code can become tedious and error prone, especially for the more common scenarios. It would be really nice if someone else could write that code and you could just focus on the core logic of your application. Thanks to a number of new designer features in Visual Studio 2005, you...

Figure 87 Setting DataSource and DataMember Properties on the FilteredGrid

This gets you the interaction you are looking for in the Properties window, but if you try to drag and drop a data source from the Data Sources window, you will still get a mouse cursor indicating the drop is not allowed circle with a slash . To remedy this, you need to add an appropriate binding attribute to the class itself.

Binding a DateTime Column to a DateTimePicker

Month Calendar Vb2008 Databiding

The DateTimePicker control is designed specifically for displaying date and time information and to give you a richer editing experience for the values by treating each of the parts of the displayed information such as month, day, year, hours, minutes, and seconds as individual values that can be set when editing through the control. Additionally, it provides a drop-down calendar control that lets a user select a date from a one-month calendar view see Figure 4.4 . Figure 4.4....

Monitoring the Data with Events

Another important capability of data-binding scenarios, especially when there are layers of decoupling involved, is getting notified when a change to the underlying data source occurs. Table 4.2 shows the events exposed by theBindingSource. Fires when the AddNew method is called to add a new item to the collection contained by the binding source. This event was discussed earlier in this chapter. Fires when each simple bound control has completed its data binding, meaning the bound control has...

Programmatic DataGridView Construction

The most common way of using the grid is with data-bound columns. When you bind to data, the grid creates columns based on the schema or properties of the data items, and generates rows in the grid for each data item found in the bound collection. If the data binding was set up statically using the designer as has been done in most of the examples in this book , the types and properties of the columns in the grid were set at design time. If the data binding is being done completely dynamically,...

Displaying Validation Errors with the ErrorProvider Control

In the example of handling the Validating event at the beginning of this chapter, I used the crude approach of popping up a message box when a validation error occurred. Although this works, it is extremely disruptive to most users to use pop-up dialogs for something like this. Windows Forms 1.0 included the ErrorProvider control that provides a standard and less obtrusive way to notify a user of an error. The error provider the ErrorProvider class control is a special kind of control, called...

Paging Through Data

Another common requirement is the need to be able to change the current record in a set of data programmatically, or in response to a user interaction that is outside of a data grid. In .NET 1 .X, the way to do this was rather obscure you had to obtain a reference to the CurrencyManager object for the data source you were working with, and then had to update thBosition property on that object to change the current record private void SetNextRecordl 1Style CurrencyManager currMgr as...

Index Cqq

SYMBOLi A i E Q i E rn t l D y W CsU E E Q EJ S y IY ififl IBindableComponent interface .NET Framework 2.0 and data-bound controls and simple data binding with IBindingList interface binding to data tables BindingList lt T gt implementation exercising change notifications filter function notifying consumers of changes overview of restricting changes to data search function 2nd sort function 2nd using for I List interface limitations IBindingListView interface adding functionality of...

Listing 25 Using a Table Adapter to Fill and Update a Data Set

CustomersTableAdapter m_Adapter new CustomersTableAdapter CustomersDataSet m_Customers new CustomersDataSet public Forml private void OnFill object sender, EventArgs e m_Adapter.Fill m_Customers. Customers m_Grid.DataSource m_Customers. Customers private void OnUpdate object sender, EventArgs e m_Adapter.Update m_Customers. Customers The code in Listing 2.5 comes from a simple Windows Forms client application. The form has two buttons on it, labeledF and Update, and a DataGridView control named...

Navigating Data Through a Binding Source

In Chapter 3 you saw that you can change the current record in the underlying data source by using a set dtflove XXX methods and the Position property. I want to review those again here while I am in the process of making you an expert on binding sources, and point out a few other methods that assist in navigating through the data contained in a binding source. Table 4.1 shows the properties and methods related to navigating through the data in the underlying data collection and describes what...

Presenting Data with the DataGridView Control

THE PRECEDING CHAPTERSshowed many detailed examples of data binding to simple bound controls and list bound controls. However, one of the most common ways of presenting data is in tabular form. Users are able to quickly scan and understand large amounts of data visually when it is presented in a table. In addition, users can interact with that data in a number of ways, including scrolling through the data, sorting the data based on columns, editing the data directly in the grid, and selecting...

The IBindingList Interface Providing Rich Binding Support

The IBindingList interface is the most important data-binding interface for supporting full-featured data binding. It defines capabilities for controlling changes to the list, sorting and searching the list, and providing change notifications when the contents of the list change. You can easily create a partial implementation oflBindingList minus sorting and searching using the BindingList lt T gt generic collection class in .NET 2.0. As mentioned earlier, implementing the I List interface is...

Basic Data Binding with the DataGridView

The easiest way to get started using the DataGridView control is to use it in basic data-binding scenarios. To do this, you first need to obtain a collection of data, typically through your business layer or data access layer. You then set the grid's data-binding properties to bind to the data collection, as described in Chapters 4 and 5. Just like with other Windows Forms controls, the recommended practice in .NET 2.0 is to always bind your actual client-side data source to an instance of the...

Listing 26 CustomersTableAdapter Partial Class Definition

public partial class CustomersTableAdapter public SqlTransaction BeginTransaction SqlConnection connection if connection.State ConnectionState.Open throw new ArgumentException Connection must be open to begin a transaction Set the connection for all the contained commands Connection connection SqlTransaction transaction connection.BeginTransaction foreach SqICommand cmd in _commandCollection if cmd null cmd.Transaction transaction if Adapter.lnsertCommand null Adapter.lnsertCommand.Transaction...

Data Binding Lifecycle

As mentioned earlier in the book, it's important to keep in mind the direction of data flows in data binding and when the data flow occurs. Formatting sends data from the data member to the control property, and parsing sends data from the bound control property to the data member. But when do these processes happen The trigger for formatting is usually when the current item in a data source is being set, or when the property in the current item for a given binding object is changed. The...

The ICustomTypeDescriptor Interface Exposing Custom Type Information

The ICustomTypeDescriptor interface lets an object provide custom type information for the information it wants to expose publicly, so that consuming code can ask the object to describe itself, rather than using raw reflection against the type definition. If you don't implement this interface, the TypeDescriptor class can describe the public properties that are defined on your object using reflection for data binding and other purposes. But if you implement this interface, you can take control...

Listing 22 Strongly Typed Access to Data in a Typed Data Set

public void UpdateCustomer CustomersDataSet custData, string custID, string compName, string contactName, string title, string phone custData. Customers. CustomerlDColumn. ColumnName CustomersDataSet.CustomersRow rows CustomersDataSet.CustomersRow ds. Customers. Select custlDColumnName ' custID CustomersDataSet.CustomerRow row rows 0 row.CompanyName compName row.ContactName contactName row.ContactTitle title row.Phone phone Although this code may look slightly more verbose due to the nested...

Adding Transaction Support to a Table Adapter

If you want to execute multiple queries through a table adapter within the scope of a single transaction, you have a couple of options. You can use the TRansactionScope class from the new System.Transactions namespace to execute the queries within a single transaction scope CustomersTableAdapter adapter new CustomersTableAdapter Start the transaction using TransactionScope scope new TransactionScope Save any changes currently in the data table adapter.Update customers First query customers 0...

Using BindingList to Create Rich Object Collections

So far we have been using the List lt T gt class for many of the custom business object collections in data-binding scenarios. And for many scenarios, creating a customer collection type using the List lt T gt generic type may be all you need. However, when you are doing data binding in Windows Forms, the BindingList lt T gt class is more powerful than theList lt T gt type, and should be the one you favor in general. One of the biggest differences is that the BindingList lt T gt class takes...

DataGridViewLinkColumn

Like the button column, this is another form of rendering a text cell that gives the user a visual cue that clicking on it will invoke some action. This column type contains cells of type DataGridViewLinkCell and renders the text in the cell to look like a hyperlink. Typically, clicking on a link navigates the user somewhere else, so you might use this kind of column if you are going to pop up another window or modify the contents of another control based on the user clicking on the link. To do...

Validation down the Control Hierarchy

As mentioned earlier, the Validate method performs validation on the currently focused control and each of its ancestors. However, a more common need is to validate all of the controls on the form in response to some event, such as the user pressing a Save or Submit button. In .NET 2.0 this becomes extremely easy, and you have a number of options to control the scope of what happens as part of the validation process. If you want to perform validation for all the controls on a form, or a subset...

DataGridViewTextBoxColumn

This is the default type of column as described earlier in this chapter , and it displays text within the contained cells, which are of type DataGridViewTextBoxCell. Data that is bound to this column type and values set on the cell have to be of a type that can be converted to a string. This column type supports editing if the Readonly property is true the default and the focus in on the cell. To enter editing mode, press F2, type in characters, or click in the cell. This embeds a separate...

Listing 63 Persisting Display Order of Columns

private void Form1_Load object sender, EventArgs e m_Grid.AllowUserToOrderColumns true SetDisplayOrder private void OnFormClosing object sender, FormClosingEventArgs e using IsolatedStorageFileStream isoStream new FileMode.Create, isoFile int displaylndices new int m_Grid.ColumnCount for int i 0 i lt m_Grid.ColumnCount i displaylndices i m_Grid.Columns i ,Displayindex XmlSerializer ser new XmlSerializer typeof int ser.Serialize isoStream,display Indices IsolatedStorageFile....

The ITypedList Interface Exposing DataBinding Properties

The ITypedList interface lets you expose or access type information about the properties that the items in a collection define. It allows consuming code to say to a collection. Tell me all about the data items that you contain. This information is used extensively by the Visual Studio designer to let you deciarativeiy configure bound controls at design time, such as configuring columns on a DataGridView control based on the typed properties of the items in the bound collection. It can also be...

Property Descriptors Allowing Dynamic Data Item Information Discovery

An important class for allowing data-binding code to work against any collection and data item type is thi'ropertyDescriptor class. This class is defined in the System.ComponentModel namespace and provides dynamic discovery of type information about the individual properties of an object. You can obtain a property descriptor in a number of ways. As discussed in the following sections, some of the data-binding interfaces have methods or properties that will return property descriptors. You can...

Where Are We Mem

This appendix has given you a very quick introduction to coding databinding scenarios using ASP.NET 2.0, and an idea of what capabilities exist and how to approach them. It isn't intended as a comprehensive lesson in data binding, but it should help get you started. This information will be important to you if you need to code similar data-bound Uls for an application when you are also building a Windows Forms version for a subset of your users.

SELECT which returns a single value Returns 3 single value for example Sum

UPDATE Changes existing data in a table. O BELETE Here you can specify whether to add a query method to select rows into the data set the default , select an individual value, or perform a delete, update, or insert. The last four options simply result in a new query method with a separate command object being added to the table adapter for performing the specified query against the underlying connection. They don't affect the data set in any way they just take in parameters and return a value....

Chaining Binding Sources for MasterDetails Data Binding

Simple data-binding scenarios are obviously very common, but situations where you need to display multiple related sets of data in a single form are too. When you do so, you'll want to keep the sets of data synchronized in terms of what the current record is in each data source. For example, consider the data schema shown in Figure 4.2. This schema has several tables defined with parent-child relations that cascade through several generations or layers of data. Figure 4.2. Hierarchical Data...

Controlling Validation Behavior with the AutoValidate Property

By default, Windows Forms 2.0 applications will behave just like previous versions if you set the Cancel property of the Validating event's CancelEventArgs argument to TRuethis prevents the focus from leaving that control and terminates the validation process, s lt Validated won't fire. This is done for backward-compatibility reasons. However, a new property has been introduced to the ContainerControl class that will let you modify this behavior if desired. If you plan to perform validation...