Getting to Know the IBinding List Members

The properties of the IBindingList interface are read-only and are described inTable 7.8. The methods of IBindingList are described in Table 7.9, and the one event inTable 7.10. Table 7.8. IBindingList Interface Properties Table 7.8. IBindingList Interface Properties True if the collection supports modification of the items in the collection, false otherwise. This is a read-only property. True if the collection supports the addition of new items, false otherwise. This is a read-only property....

Data Bound Controls

Most of the controls that ship with.NET Framework support data binding to some degree, because they all inherit from the Control base class, which implements the IBindableComponent interface. That interface defines the contract for supporting a collection of simple binding objects (instances of the Binding class) through a DataBindings collection on the component that implements the interface. The interface also allows the implementing component to be associated with a BindingContext, which...

Listing 86 OnFilter Clicked Event Handler

Private void OnFilterClicked(object sender, EventArgs e) if (m_BindingSource.List.Count < 0 m_FieldsCombo.Items.Count < 0) return m_BindingSource.Filter null return Set filtering flag m_FilterlnProgress true string filterMember m_FieldsCombo.Selectedltem.ToString() object dataltem m_BindingSource.List Oj PropertyDescriptorCollection props PropertyDescriptor propDesc props.Find(filterMember, true) m_BindingSource.Filter string. Format( 0 ' 1 ', propDesc.Name, m_FilterTextBox.Text) To do the...

Merging Data from Multiple Data Sets

The DataSet class also supports a couple of ways of moving data between different data sets. Your first instinct might be to simply get a DataRow reference from one data set, perhaps from aSelect operation or from iterating through, and then add that to the table in another data set. Unfortunately, this isn't allowed and will throw an exception. When a data row is added to a table, it becomes a part of that table, and it cannot belong to more than one table at a time. Only a row that has been...

Next

Creating Typed Data Sets with the Data Set Designer To help you become familiar with the Visual Studio features for creating typed data sets, the following sections step you through the process of creating a data access layer for parts of the Northwind database. You need to 1. Create a data access layer class library project and add a typed data set definition to it, and set up a data connection in Server Explorer for the database you will work with. 2. Add tables to the data set by dragging...

The lEnumerable and lEnumerator Interfaces Supporting Iteration Through Collections

Implement lEnumerable to allow consumers of your collection to iterate through all of the objects in the collection in various ways. When you implement lEnumerable, you also have to implement lEnumerator on at least one class and return an instance of that class from the I Enumerable. GetEnumerator method. The implementation of I Enumerator provides the methods and properties that let you iterate over the collection. You can provide multiple implementations of I Enumerator to allow different...

Capturing Data Errors on Data Sets

Data sets and their child data objects, such as data tables and rows, have built-in support for keeping track of data errors. The DataRow class exposes a string RowError property that you can set to an error message to indicate that an error has occurred somewhere in that row and give descriptive information about the error. To be more specific, you should also set error information associated with the individual data fields that are the cause of the error if appropriate. To do that, you call...

Binding a Numeric Column to a Text Box

Setting up binding for a numeric column to a TextBox control is very similar to doing it for aDateTime column. The main difference is in the formatting strings that you use to specify the output format in the text box. You can again provide the format string either through the Binding constructor or by setting theFormatString property on the Binding object. You can also use one of the overloadedAdd methods on the DataBindings collection. The following code demonstrates the latter approach....

Typed Data Set Internals

Before discussing how to create the typed data sets, let's look at what is generated when you do create them. Lots of examples in this book use them, and knowing what will be in a given typed data set based on some knowledge of the schema from whence it came will help you unravel the mysteries of typed data sets. A typed data set is implemented as a set of classes derived from the basic classes that compose a data set. You get a class derived from the DataSet itself, and a class derived from...

Master Details Data Binding

Often you will work with data collections that have parent-child relationships. For example, a Customer may have a collection of Orders that they have placed, and each Order will have a collection of Order Detail objects that describe the items in that Order. In this situation, you often want to provide users with a way to view the collection of parent objects, and when they select a parent object, for them to see just the associated child objects. This often involves two tables in a data set...

Windows Forms Validation

Validation is all about checking input from the user and making sure it is valid, based on some criteria that you, as the application designer, determine. Examples of validation checks include Checking for required input in a particular field Checking whether input data is a valid numeric value Checking for input to be within some range of values Checking for particular patterns within an input string Invoking complex business rules that check dependencies between other business entities and...

Figure 23 Adding a Typed Dataset Definition to a Project

Ad ri New Item Hilf (hwi nriDafafrm s-s i-tij l S-TLuhn imfihillrd trmpirttd A DdtiSrt for Lriiftg data in y Aw e Jk ti r Name the data setCustomersDataSet and click theAdd button. This adds a CustomersDataSet.xsd file to your project and opens the data set designer with a blank canvas. You can manually add items to a data set definition by dragging and dropping components from the Toolbox to the design surface, in the same way you design Windows Forms using the Toolbox and the design surface...

Autocompleting Input in a Text Box Control

The next requirement to tackle is not directly related to data binding, but is a common requirement for data input applications the capability to autocomplete user input as they type it within input controls such as a TextBox or ComboBox control. This is a new capability provided in .NET 2.0, so let's use it to enhance the filtered grid functionality. 1. To enable autocomplete for a text box, you need to set the AutoCompleteMode property to something other than its default value of None. The...

About the Author

BRIAN NOYES ISa software architect, trainer, writer, and speaker with IDesign, Inc.Mww. design.net), a premier .NET architecture and design consulting and training company. He has been developing software systems for more than fifteen years, speaks at many major software conferences around the world, and writes for a variety of software journals and magazines. He is based in Alexandria, Virginia, but is a Southern California surf bum at heart, having grown up there. Prior to becoming a full...

The ISupportlnitialize Notification Interface Supporting Interdependent Component Initialization

The ISupportlnitializeNotification interface lets interdependent child objects be notified when other objects have completed initialization. This allows an object that depends on another object's state to wait until the other object has completed its own initialization before the dependent object tries to complete its own initialization. The ISupportlnitialize interface just discussed helps you work with components with interdependent properties on a single component. But what if you have...

Listing B1 OnStartingUp Method

Protected override void OnStartingUp(StartingUpCancelEventArgs e) Window win new Wndow() win.Wdth 350 win.Height 200 win.Text Login Sample from Code Create the controls Grid grid new Grid() TextBlock userNameLabel new TextBlock() userNameLabel.TextContent Username userNameLabel.VerticalAlignment VerticalAlignment.Center userNameLabel.HorizontalAlignment HorizontalAlignment. Center TextBlock passwordLabel new TextBlock() passwordLabel.TextContent Password passwordLabel.VerticalAlignment...

Custom Column Content with Unbound Columns

Now that you understand how to programmatically create columns and rows, and populate them with values, you may be wondering if you have to go to all that trouble any time you want to present content in a cell that isn't bound to data. The good news is that there is a faster way for most scenarios where you want to present unbound data. You will need to programmatically create all the columns in the grid (although you can get the designer to write this code for you too, as shown later), but you...

Creating a Grouped Column Data GridView

As an example of creating a custom data-bound control by deriving a class from an existing Framework control, let's create a specialized DataGridView control that presents its bound data as grouped data items within each column. For example, say you have a table containing summary data of all the products ordered by each customer by date. Each customer may have multiple orders for the same product, and multiple orders might have been placed by each customer on a given date. If you sort the data...

System Requirements

This book was written with the code base of .NET 2.0 and Visual Studio 2005 over the course of Beta 1, several Community Technical Previews, and ultimately Beta 2. The code presented in this book runs with Beta 2. I worked closely with the Windows Client product team at Microsoft, and there are no feature changes planned between Beta 2 and product release. However, some minor syntax may change between production and the release of .NET 2.0. If they do affect the code or concepts, I will provide...

Listing 62 Virtual Mode Sample

Partial dass VirtualModeForm Form private List< DataObject> m_Data new List< DataObject> () private List< bool> m_Visited new List< bool> () m_Grid.CellValueNeeded + OnCellValueNeeded m_GetVisitedCountButton.Click + OnGetVisitedCount lnitData() lnitGrid() for (int i 0 i < 1000001 i++) m_Visited.Add(false) DataObject obj new DataObject() obj.ld i obj.Val 2 * i m_Data.Add(obj) m_Grid.VirtualMode true m_Grid. Readonly true m_Grid.AllowUserToAddRows false...

NET Framework Generic Collection Classes

In .NET 1.1, you implemented custom collection classes using the CollectionBase class and its underlyingArrayList. This had some problems, because everything was stored and accessed as a raw Object reference under the covers, which incurs performance problems due to boxing and unboxing of value types and casting of any type. One of the most important new features at a Framework level in .NET 2.0 is the introduction of generics. You have already seen the use of generics in a number of samples in...

Raising Item Changed Events

One other interface is implemented on the BindingList< T> class that you might want to override for advanced scenarios in your custom collection classes the IRaiseltemChangedEvents interface. This interface has a single Boolean property,RaiseltemChangedEvents, defined on it. In the BindingList< T> class implementation, this property returnsfalse, but you can override it in a derived class if desired. If you return true to indicate that you do raise item changed events, it is expected...

Smarter Child Parent Data Binding

If you've spent any time looking at the BindingEvents application, you are probably thinking that there must be a better way to handle this particular data-binding scenario than what has been presented in the preceding sectionsand you're right. What I've showed so far was more to illustrate the use of the formatting and parsing events, not the cleanest way to address the scenario. If you step back from the existing code and analyze the data-binding scenario, what you really need for the...

Windows Forms Designer Generated Code New in

In the previous section, I mentioned that all your designer interactions were really just generating code for you. But when you went into Code view for the Forml .cs file, you didn't see much there besides the constructor for the form calling some method called InitializeComponent and the event handler method that you created through the Properties window. So where is all the code going that declares the member variables for the controls, sets their properties, hooks up the event, and so on The...

Adding Data Sources to a Project

Visual Studio automatically adds any typed data set definitions that are part of your project to the Data Sources window. It also adds objects returned from any Web references that are part of your project to the Data Sources window. However, you don't necessarily have to add these things to your project before you start using the Data Sources window, because you can create connections to data sources directly from the window itself. When you add a data source through the Data Sources window to...

Underneath the Covers of Data Binding for Complex Types

Binding text and integer data to grids and controls rarely presents a challenge once you know the basic approach to Windows Forms data binding. But what does get a little trickier is presenting things like floating point numeric types, dates, and images that are stored in the database. The problem with these types is that their format in the database or in the custom objects doesn't necessarily map directly to the way that you would present them. For example, when storing a graphic image in the...

Listing 34 Text Box Data Bindings

Private void AddTextBoxDataBindings(CustomersDataSet nwData) Data Table table nwData.Customers table, CustomerlD, true) table, CompanyName, true) table, ContactName, true) table, Phone, true) This code adds a new entry in theDataBindings collection for each of a series of text boxes on the form. ThdDataBinding property exposes a reference to an object of type ControlBindingsCollection. This collection class exposes an overloadedAdd method that allows you to set up each data binding in a single...

Customers ContactName true mPhone TextBox DataBindings AddText nwData Customers Phone true

In this case, since the data source is the data set itself, you have to specify the column to bind to by prefacing the column name with the table name, separated with a dot in the same way you use a dot with members of types in .NET code. If you made just this change in the SimpleNorthwindClient sample application and ran it again, the data in the text boxes would initially present the data for the first row just fine. But if you clicked on another row in the grid, you would see that the text...

Listing 33 Using Selected Value from a Data Bound Combo Box

Public partial class SelectedValueForm Form private void OnFormLoad(object sender, EventArgs e) m_CustomersDataSet CustomersDataSet.GetCustomers() Set up the bindings for the combo boxes m_CompanyNameCombo.DataSource m_CustomersDataSet. Customers m_CompanyNameCombo.DisplayMember CompanyName m_CompanyNameCombo.ValueMember CustomerlD m_ContactNameCombo.DataSource m_CustomersDataSet.Customers m_ContactNameCombo.DisplayMember ContactName m_ContactNameCombo.ValueMember Phone Hook up event handlers...

Layered Application Architecture

Architecture Visual Basic

I have already mentioned layers in your application several times in this chapter, and I will continue to do so throughout the book. Layered application architecture is a very important concept and something you should consider adopting in any nontrivial application. In layered application architecture, you divide the functions of your application into separate layers. The number of layers you choose is up to you, but the most common approach is to separate your application into presentation,...

Command and Control of Your Windows Forms Applications New in

Three new controls that you will probably want to use in almost every Windows Forms application you write are the MenuStrip, ToolStrip, and StatusStrip controls. These controls are new in .NET 2.0 and replace their predecessorsiyiainMenu, ToolBar, andStatusBar) from .NET 1 .X. Like the Splitter mentioned earlier, the old controls are still part of the Framework for backward compatibility. However, for any new applications you design, you should start using the three strip controls as your...

Introduction to Table Adapters

As you saw at the bottom of the table definition in Figure 2.7. there was something attached in the designer labeled CustomersTableAdapter that contains two displayed methods namedFill and GeTData. This additional class that gets generated for each table in your typed data set is called a table adapter. The table adapter, new in .NET 2.0, greatly enhances the experience of working with typed data sets. As discussed earlier in this chapter, prior to .NET 2.0, when you wanted to fill a data set...

Extended Validation Controls

The good thing about the validation events model and theErrorProvider control is that they are simple and straightforward to use. The bad thing about them is that to cover every control in a complex form requires a ton of separate event handlers, and each one has to contain the custom code that looks at the value being validated and makes a decision about its validity and what to do about it. Validation code can do any number of things, but it typically takes on certain patterns for most cases....

Scoping Transactions with System Transactions

A whole new approach to writing transactional code was designed into .NET 2.0 in the System.Transactions namespace. Through the classes defined in that namespace, you can now easily start or join transactions in your code without being tied directly to the transactional capabilities of the database or other specific transactional resource managers. The transactions that are created through the System.Transactions classes can be either lightweight transactions against a single resource manager,...

Understanding Data Binding Interfaces

TO REALLY UNDERSTAND data binding and how to implement either custom data sources or custom data-bound controls, you first have to understand the interface-based contracts that drive data binding. This chapter describes each of the key interfaces that are involved in data binding from the perspective of the contract that the interface represents. It discusses the purpose of the interface, when it is used, and what the interface defines. This chapter is less hands-on than most of the other...

Updating Data Sources Through Data Binding

As you saw in Listing 3.4. when you have controls bound to a data source in Windows Forms, you can get automatic updating of the underlying data source in memory two-way data binding if changes are made through the bound controls. This is true whether the data source is bound to a grid or to individual controls, such as text boxes, that let the user change the presented data values. The data source has to support certain interfaces to allow changes made in the bound control to be propagated...

Loading Data into an XPath Document

There are two common ways of getting XML data into an XPathDocument. The first is from a file, which is a simple matter of passing the file path or URL to the constructor of the XPathDocument class XPathDocument doc new XPathDocument doc.xml The constructor can also take a stream, an XmlReader, or aTexTReader. Whichever you use, the contents of the document will be loaded into memory and parsed into the underlying object model of the XPathDocument. To get the data out of SQL Server, you can...

Figure D4 The Making of a Concurrency Violation

You could allow a last-in-wins strategy, and always blindly write the values of an update to the row without considering its current contents. This is effectively no concurrency control. If you did this with the scenario in Figure D.4, the changes made by client 2 would be lost. If you are working with a connected data model, there are a number of ways to handle this situation with server-side locks on tables or rows that prevent concurrent access or updates depending on the level of isolation...

Speciy a Select stafcernent to load data O Create new stared procedure

Speciy a SELECT statement and the wizard will generate a new stored procedure to select records. Use existing stored procedure choose an existing stored procedure. You can choose whether to base the query method you are adding on a new SQL statement, on a new stored procedure, or on an existing stored procedure that is already defined in the database. For this example, let's define a new SQL statement. After selecting or accepting the Use SQL statements option, click the Next button. This...

Getting to Know the Binding Source Component

The BindingSource component solves a number of tricky problems that surfaced with the approach of directly binding data sources to controls in .NET 1 .X. It provides a layer of indirection between a data source and bound controls that makes a number of things easier. Additionally, it surfaces important control points and access to the underlying data source in a way that saves you from having to delve into the data-binding mechanisms of a form the way you had to in the past. A binding source...

Binding a Date Time Column to a Text Box

Developers frequently choose to use a simple text box control for date and time display and input. In part this is due to the data-binding problems experienced with the DateTimePicker control in .NET 1.1 and to the remaining problems with dealing with nulls. But it can also be to simply have explicit control over the display and input values. Presenting a drop-down calendar as shown in Figure 4.4 doesn't make a lot of sense if the control is only going to display times. Unfortunately, the...

Listing 31 Combo Box Data Binding

Public void OnFormLoad object sender, EventArgs args CustomersDataSet dataSource new CustomersDataSet CustomersTableAdapter adapter new CustomersTableAdapter adapter. Fill dataSource m_Combo. DataSource dataSource.Customers m_Combo. DisplayMember CompanyName m_Combo.ValueMember CustomerlD Listing 3.1 sets the DataSource property on aComboBox control to the Customers table within a typed data set, which implements the I List interface and is the complex binding data source. TheDisplayMember...

Managing Transacted Additions to a Collection

If you are supporting transacted editing of an object, you will usually also want to support transacted addition of the object type to whatever collection it belongs to. As mentioned before, if you are using the BindingList lt T gt class for your custom collections, you already get transacted additions for free through the combination of the AddNew method and the implementation of thelCancelAddNew interface methods EndNew and CancelNew. However, if the control that you are bound to doesn't know...

Manipulating Data Through a Binding Source

The binding source itself gives you indirect access to the data that is stored in the underlying client-side data source. Once you set the DataSource property on a binding source, you don't have to maintain a reference to the data source object itself, because one will be maintained by the binding source. You can always retrieve a reference to the data source by casting the DataSource property to the expected type. The only downside of this approach is that you have to make sure that at the...

The ICollection Interface Controlling Access to a Collection

You can use the ICollection interface to find out how many items exist within a collection, copy the items from a collection into an array, discover whether the collection provides synchronization for multithreaded scenarios, or access the synchronization object for the collection to implement your own synchronization locking. The next collection-oriented interface up the inheritance hierarchy from Enumerable is the ICollection interface. ICollection is derived from Enumerable, so to implement...

Index

SYMBOLi A i E B i E rn t l ID y M CsU E E Q EJ S y IY W adding helper methods in layered application architecture table adapters and Data adapters loading data sets from database and updating database with using Update method on Data binding .NET Framework 2.0 and adding to custom controls building applictions with Windows Forms See Windows Forms applications, building data-boundl business objects See Business objects key interfaces involved in See Interfaces master-details paging through data...

Object DataSource Control

The ObjectDataSource control is the solution to the tight coupling that is caused by usingSqIDataSources in your pages. Using the ObjectDataSource control, you can easily bind controls on your page to any source of data, such as custom business objects and collections in a layered application architecture. You set the ObjectDataSource control'sTypeName property to the fully qualified type name of a class, and that class should have a method that returns a collection of the objects you want to...

The ISupportlnitialize Interface Supporting Designer Initialization

The ISupportlnitialize interface lets controls defer acting on values set on interdependent properties until the container tells the control that all values have been set. This avoids having a control try to take actions based on a property's setting if those actions might fail if another property needs to be set first, and those properties can be set in any order. The Windows Forms designer uses this interface, so the code it generates to set properties doesn't need any insight into the...

Generating Data Bindings with Smart Tags

Smart Tags, a new feature in the Visual Studio 2005 Forms designer, let you access commonly used property settings and actions on a control or component in the designer, instead of having to go through the Properties window or a menu item. You access a Smart Tag by clicking on the small triangular glyph that displays on the upper right edge of the control or component when you click on it see Figure 5.20 . Figure 5.20. Binding Source Smart Tag Figure 5.20. Binding Source Smart Tag Depending on...

Listing 45 Populating a Binding Source Object with a Data Reader

Private void OnFormLoad object sender, EventArgs e SqIConnection conn new SqlConnection SQL Server 2005 Express connection SqIConnection conn new SqlConnection SqICommand cmd new SqlCommand SELECT CustomerlD, CompanyName, ContactName, Phone FROM Customers, conn SqIDataReader reader cmd.ExecuteReader m_CustomersBindingSource. DataSource reader Using a data reader in this way has several advantages and disadvantages. The advantage is speeda data reader is about the fastest possible way to get...

Figure 522 Form with Search Tool Strip Added by the Designer

The Add Query functionality only works for typed data sets that are part of your Windows Forms projects. If you want to set up the same functionality for a data set that is defined in another assembly, such as a data access layer assembly, you will have to manually add the query to the table adapter as described in Chapter 3 , add theToolStrip and its controls to the form manually, and then write the code to execute the query method on the table adapter and put the results in the corresponding...

Updating Parent Data Bound Controls from Child Data Bound Controls

The trick to reversing master-details scenarios like this is to synchronize the controls bound to parent data items based on the selection of child data items. In this case, the individual data items are rows in two different tables. Those tables have a parent-child relation from the parent Country table to the child ExchangeRates table based on the foreign key constraints from the CountryFromID and Country TolD columns of the ExchangeRates table to the CountrylD column of the Countries table....

Cancel

Using the property fields in this dialog, you can set fine-grained options for how the cell will display its content, and you can even see what it is going to look like in the Preview pane at the bottom of the dialog. You can also set border styles for cells using the grid's CellBorderStyle, ColumnHeadersBorderStyle, and RowHeadersBorderStyle properties. Using these styles, you can achieve some fairly sophisticated grid appearances, as seen in Figure 6.13. In this sample, default cell styles...

Listing A3 Data Bound Grid View 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...

Listing 36 Connecting Data Sources to Controls with a Binding Source

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

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...

Date TimePicker 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 Data GridView OnCell Formatting 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 D6 XPath Navigator 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...

Table D5 XPath Navigator 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...

Data GridView ComboBox Column

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...

Data Binding 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 ICancel AddNew 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 IBinding List

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

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...

Data GridView 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 Data Source and Data Member Properties on the Filtered Grid Control

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 Date Time Column to a Date TimePicker

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 Data GridView 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 Error Provider Control

Errorprovider

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...

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

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 Data GridView 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 IBinding List 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 Data GridView

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 Customers TableAdapter 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 ICustom TypeDescriptor 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

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 Binding List 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...

Data GridView LinkColumn

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...

Data GridView TextBox Column

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 ITyped List Interface Exposing Data Binding 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

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 Count or any other aggregate Puncton

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 Master Details 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 Auto Validate 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...

Filling a Binding Source with a Data Reader

Another opportunity that opens up with the binding source that wasn't really an option before in Windows Forms is the ability to bind controls indirectly to data coming from a data reader. If you execute a data reader through a command object, you can set a binding source's DataSource property to that data reader. The binding source will iterate through the data reader's contents and use it to quickly populate the binding source's List collection. Then, as long as you execute the data reader...