Home > Store > Programming > Windows Programming

Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET

Register your product to gain access to bonus material or receive a coupon.

Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET

Best Value Purchase

Book + eBook Bundle

  • Your Price: $70.19
  • List Price: $116.98
  • Includes EPUB, MOBI, and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    MOBI MOBI The eBook format compatible with the Amazon Kindle and Amazon Kindle applications.

    Adobe Reader PDF The popular standard, used most often with the free Adobe® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

More Purchase Options

Book

  • Your Price: $51.99
  • List Price: $64.99
  • Usually ships in 24 hours.

eBook (Watermarked)

  • Your Price: $41.59
  • List Price: $51.99
  • Includes EPUB, MOBI, and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    MOBI MOBI The eBook format compatible with the Amazon Kindle and Amazon Kindle applications.

    Adobe Reader PDF The popular standard, used most often with the free Adobe® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

Description

  • Copyright 2006
  • Dimensions: 7x9-1/4
  • Pages: 736
  • Edition: 1st
  • Book
  • ISBN-10: 0-321-26892-X
  • ISBN-13: 978-0-321-26892-1

“Brian Noyes’ writing style easily captures your attention as he elaborates on all aspects of data binding in his book. He has a refreshingly clear and crisp delivery as he starts each chapter with a simple tour of each topic, and then leads you into practical concerns for sound practices and extensibility opportunities. Most importantly, as Brian explains approaches to data-binding architecture, patterns of usage, the value of data sets, binding controls and the rest, he always describes how he reaches his recommendations on the topic. This book is perfect for newcomers to .NET 2.0, but also for those that have some experience. Anyone who cares about data in their applications (okay, that should be almost everyone) is guaranteed to learn something new and useful by reading Brian’s book.”
—Michele Leroux Bustamante, IDesign chief architect, Microsoft regional director, and MVP
“Brian has saved me a lot of time. I’m writing The Hitchhiker’s Guide to Visual Studio and SQL Server 2005 (7th Edition) and I’m not going to have to cover data binding nearly as deeply because Brian has done it for me. His book gets right to the meat of the subject and makes data binding look easy. I was also pleased to see that the book focuses on the misunderstood and under-applied Windows Forms architecture. It’s a must-read for anyone trying to make their application more interactive and to leverage the new Visual Studio 2005 technology. I’m planning to point my readers to this resource when they need an in-depth treatment of data binding.”
—William Vaughn, president, Beta V Corporation
“Data binding has finally come of age in Windows applications. Back in the Visual Studio 6.0 days, I ignored data binding completely and wrote my own repetitive code to encapsulate my business logic. With Visual Studio 2005, we finally have a robust and compelling data-binding technology. To ignore it today would make you inefficient and put you behind the curve. Brian delivers a clear and concise discussion of a core topic of development for Windows today. A combination of an easy-to-follow conversational yet technical tone, excellent examples, and solid explanations make this a must-read for any developer writing for Windows or learning to write for Windows.”
—Stephen Forte, chief technical officer, Corzen Inc.
“This book provides a clear, readable, and in-depth treatment of data binding, with detailed discussions of best practices in the presentation and use of data. Brian communicates his knowledge on the mechanics of data binding to give the low-level understanding that makes all the difference when building sophisticated applications and troubleshooting difficult problems. Effective data binding can enormously reduce the amount of code in your applications and will allow new levels of sophistication in your development. Read this book.”
—Jonathan Cogley, chief executive officer, Thycotic, ASPInsider, and C# MVP
“The .NET Framework 2.0, Visual Studio .NET 2005, and Windows Forms 2.0 incorporate the most powerful data-binding platform yet, and absolutely need a book like this to expose it. Brian’s extensive data-binding knowledge and experience shine through as he comprehensively explores its many facets, starting with the fundamentals before tackling a wide variety of real-world scenarios. I’ve always thought a data-binding book was necessary, and I’m glad Brian found the time to write his.”
—Michael Weinhardt, freelance author and application developer
Data Binding with Windows Forms 2.0 earns a gold star and a prized place in my development book library. Brian is an exceptional teacher of technology, best practices, and technique. He continues to educate at every presentation I attend; his book carries that quality to paper. I found this book to be highly informative and full of all the important steps and examples necessary to learn this technology. In this book, Brian demonstrates a firm grasp on the concepts and I really enjoy his efforts to promote best practices at every chance. Definitively a cover-to-cover read.”
—Randy Hayes, president, Expert Network Solutions, Inc.
“Brian’s direct and well-organized presentation makes this much misunderstood topic finally understandable.”
—Sahil Malik, author of Pro ADO.NET 2.0 and C# MVP

Data binding is the most important part of many business applications—and one of the most difficult things to understand. Data Binding with Windows Forms 2.0 is the first book to focus on this crucial area of development. It will quickly get you up to speed on binding data sources to Windows Forms components. The book contains clear examples in C# that work with SQL Server 2000 and SQL Server 2005. Visual Basic .NET examples are available on the book’s Web site.

Brian Noyes, leading consultant and speaker on .NET programming, teaches you both the theory and practice of data binding and provides numerous samples ready to run in Visual Studio 2005.

From his in-depth coverage, you’ll learn how to

  • Use Visual Studio 2005 to generate a data-bound application from a database
  • Use the new Visual Studio 2005 typed data set designer, and how and why to use typed data sets and typed data adapters
  • Perform simple and complex binding of data to controls, and how to use the .NET 2.0 BindingSource
  • Use the Binding object for simple binding with automatic formatting, and how to handle binding events
  • Generate bound controls with the Visual Studio Designer, and how to use Data Sources
  • Present data with the new DataGridView control, and how to implement advanced features of the DataGridView
  • Implement custom data-bound controls in Windows Forms
  • Create custom business objects and collections that are suitable for use in data binding
  • Implement validation and error handling at the Windows Forms and data-binding levels
  • Implement data binding with ASP.NET 2.0 and the upcoming Windows Presentation Foundation (Avalon) technologies


Downloads

Supplements

Untitled Document

Document to Support Non-Standard Development Configurations

The samples in Data Binding with Windows Forms 2.0 assume you have a default instance of SQL Server 2000 or 2005 installed, and that the Northwind database is installed on that default instance. If you have that configuration, the downloadable samples should run withouth modification. If not, you will need to perform extra steps. Download this PDF to get instructions.

Extras

Author's Site

Untitled Document Visit the author's web site to access the book's samples and code.

Sample Content

Online Sample Chapter

Presenting Data with the DataGridView Control in .NET 2.0

Downloadable Sample Chapter

Download the Sample Chapter related to this title.

Table of Contents

Foreword xxi

Preface xxiii

Acknowledgments xxxv

About the Author xxxvii

Chapter 1: Building Data-Bound Applications with Windows Forms 1

What Is Data Binding? 2

Your First Data-Bound Windows Forms 2.0 Application 3

Data-Binding Landscape 14

Data Sources 15

Data Objects and Collections 16

DataSets or Not, That Is the Question... 18

Data-Bound Controls 20

Layered Application Architecture 21

What Is a Smart Client? 27

Where Are We? 28

Chapter 2: Working with Typed Data Sets and Table Adapters 31

A Quick Review of DataSets 31

The Quest for Type Safety 34

Typed Data Set Internals 37

Creating Typed Data Sets 41

Creating Typed Data Sets with the Data Set Designer 42

Typed Data Set-Generated Code 49

Introduction to Table Adapters 52

Filling and Updating a Typed Data Set with a Table Adapter 56

Connection Management 58

Adding Transaction Support to a Table Adapter 62

Adding Helper Data Access Methods 66

Basing Table Adapters on Stored Procedures or Views 67

Adding Queries to Table Adapters 69

Creating Typed Data Sets with Command Line Tools 77

Using Typed Data Sets in Your Code 78

Where Are We? 79

Chapter 3: Introducing Data Binding in Windows Forms 81

The 40,000-Foot View of Data Binding 81

Binding Data Collections to a Grid 86

Binding Data Collections to Multi-Valued Controls 88

Binding Data to Individual Controls on a Form 90

Data Paths Within Data Sources 92

Synchronizing Data Between Controls 96

Smarter Data Containment 97

Paging Through Data 99

Master-Details Data Binding 104

Updating Data Sources Through Data Binding 106

Where Are We? 108

Chapter 4: Binding Controls to Data Sources 111

Getting to Know the BindingSource Component 111

Simple Data Binding with Binding Sources 112

Chaining Binding Sources for Master-Details Data Binding 116

Navigating Data Through a Binding Source 121

Manipulating Data Through a Binding Source 122

Using a Binding Source as a Data Storage Container 124

Filling a Binding Source with a Data Reader 126

Sorting, Searching, and Filtering Presented Data with a Binding Source 128

Monitoring the Data with Events 131

Restricting Changes to the Data 133

Underneath the Covers of Data Binding for Complex Types 134

Binding an Image Column to a PictureBox Control 141

Binding a DateTime Column to a DateTimePicker 142

Binding a DateTime Column to a TextBox 144

Binding a Numeric Column to a TextBox 145

Automatic Formatting and Parsing Summary 147

Going Beyond Built-In Type Conversion with Binding Events 148

Handling the Format Event 154

Handling the Parse Event 156

Completing the Editing Process 157

Making the User’s Life Easier with AutoComplete 160

Data Binding Lifecycle 162

Smarter Child-Parent Data Binding 163

Binding to Multiple Copies of Data 165

Updating Parent Data-Bound Controls from Child Data-Bound Controls 168

Synchronizing Many-to-Many Related Collections 172

Where Are We? 176

Chapter 5: Generating Bound Controls with the Visual Studio Designer 177

Working with the Data Sources Window 177

Adding Data Sources to a Project 179

Choosing the Type of Data Source 180

Adding a Database Data Source 181

Adding a Web Service Data Source 185

Adding an Object Data Source 186

Generating Bound Controls from Data Sources 189

Selecting the Bound Control Type 196

Customizing the Bound Control Types 196

Binding Existing Controls to Data Sources 199

Behind the Scenes: Designer Code and Data Sources Files 202

Other Designer Data-Binding Code Generation 205

Setting Control Data Binding Through the Properties Window 206

Generating Data Bindings with Smart Tags 210

Generating Master-Details Data-Bound Controls with the Designer 214

Where Are We? 216

Chapter 6: Presenting Data with the DataGridView Control 217

DataGridView Overview 218

Basic Data Binding with the DataGridView 219

Controlling Modifications to Data in the Grid 221

Programmatic DataGridView Construction 222

Custom Column Content with Unbound Columns 226

Displaying Computed Data in Virtual Mode 233

Using the Built-In Column Types 241

Built-In Header Cells 255

Handling Grid Data Edits 256

Automatic Column Sizing 259

Column and Row Freezing 262

Using the Designer to Define Grids 263

Column Reordering 266

Defining Custom Column and Cell Types 269

Utilizing Cell-Oriented Grid Features 277

Formatting with Styles 281

Where Are We? 284

Chapter 7: Understanding Data-Binding Interfaces 285

What Does Data Binding Have to Do with Interfaces? 286

The IEnumerable and IEnumerator Interfaces: Supporting Iteration Through Collections 289

The ICollection Interface: Controlling Access to a Collection 295

The IList Interface: Enabling Data Binding 298

The IListSource Interface: Exposing Collections of Collections 303

Property Descriptors: Allowing Dynamic Data Item Information Discovery 305

The ITypedList Interface: Exposing Data-Binding Properties 307

The IBindingList Interface: Providing Rich Binding Support 310

The IBindingListView Interface: Supporting Advanced Sorting and Filtering 323

The ICancelAddNew Interface: Supporting Transactional Inserts in a Collection 325

The IRaiseItemChangedEvents Interface: Providing Item Modification Notifications on Collections 327

The IEditableObject Interface: Supporting Transactional Item Modifications 328

The INotifyPropertyChanged Interface: Publishing Item Change Notifications 329

The ICustomTypeDescriptor Interface: Exposing Custom Type Information 332

The ISupportInitialize Interface: Supporting Designer Initialization 334

The IDataErrorInfo Interface: Providing Error Information 330

The ISupportInitializeNotification Interface: Supporting Interdependent Component Initialization 337

The ICurrencyManagerProvider Interface: Exposing a Data Container’s CurrencyManager 341

Where Are We? 341

Chapter 8: Implementing Custom Data-Bound Controls 343

Extending Framework Data-Bound Controls 344

Creating a Grouped Column DataGridView 345

Using Custom Controls 350

The User Control Test Container 352

Developing Data-Bound Container Controls 353

Building a Filtered Grid Control 354

Adding Data-Binding Capability to a Custom Control 357

Supporting Designer Initialization of Data Binding 359

Specifying Binding Properties on a Control 360

Supporting Delayed Initialization with ISupportInitialize 362

Dynamically Determining the Properties of a Data Source 367

Autocompleting Input in a TextBox Control 371

Autosizing Columns in the Grid 375

Winding Up the Filtered Grid Example 376

Building a Custom Data-Bound Control from Scratch 379

Building a Data-Bound Charting Control for Decision Support 379

Coding a Data-Bound Custom Control 384

Adding Editing Support to a Custom Data Bound Control 391

Where Are We? 397

Chapter 9: Implementing Custom Data-Bound Business Objects and Collections 399

Defining and Working with Data-Bound Business Objects 400

Defining and Working with Data-Bound Business Object Collections 405

.NET Framework Generic Collection Classes 406

The CustomBusinessObjects Example 408

Setting the Textual Data-Binding Behavior of Custom Objects 415

Supporting Transacted Object Editing with IEditableObject 416

Supporting Object Edit Notifications with Property Change Events 420

Supporting Object Edit Notifications with INotifyPropertyChanged 423

Using BindingList<T> to Create Rich Object Collections 424

Creating a Custom Collection Type Based on BindingList<T> 426

Managing Transacted Additions to a Collection 439

Raising Item Changed Events 441

Adding IBindingListView Functionality 443

Binding to Business Objects Through the Data Sources Window 453

Where Are We? 455

Chapter 10: Validating Data Input and Handling Errors 457

Windows Forms Validation 458

Handling Validation Events 459

DataGridView Validation Events 462

Validation Up the Control Hierarchy 463

Displaying Validation Errors with the ErrorProvider Control 464

DataGridView Error Displays 467

DataGridView DataError Event 468

Controlling Validation Behavior with the AutoValidate Property 471

Validation down the Control Hierarchy 472

Extended Validation Controls 474

Capturing Data Errors on Data Sets 475

Providing Error Information from Custom Objects with IDataErrorInfo 479

Data Concurrency Resolution 483

Where Are We? 484

Appendix A: Binding to Data in ASP.NET 487

ASP.NET Page Processing Basics 489

Data Binding in ASP.NET 1.X 490

Data-Binding Overview in ASP.NET 2.0 498

Data Sources 499

Data-Binding Expressions 508

GridView Control 509

DetailsView Control 512

FormView Control 514

Master-Details Binding 515

Hierarchical Binding 518

Where Are We? 519

Appendix B: Binding Data in WinFx Applications 521

WinFx UI Programming and Capabilities Overview 522

Writing a Simple WinFx Application 525

WinFx Data Binding 101 532

Data Contexts and Data Sources 536

What About XAML? 537

Binding a Collection to a Grid with Templates 541

Control Styling in WinFx 543

Where Are We? 545

Appendix C: Programming Windows Forms Applications 547

Your First Windows Forms Data Application 548

Creating Windows Forms Applications with Visual Studio 554

Windows Forms Designer-Generated Code (New in 2.0) 563

A Brief Tour of the Windows Forms Architecture 567

The Dawn of .NET Execution—The Main Method 570

Handling Control Events 574

Displaying Other Forms 576

Containing Forms Within a Parent Form 577

Common Data Display Controls 578

Creating a Custom User Control 586

Laying Out Controls on a Form 589

Setting Tab Order 596

Command and Control of Your Windows Forms Applications (New in 2.0) 598

Where Are We? 600

Appendix D: Accessing Data with ADO.NET 601

Relational Data Access 603

The Ubiquitous DataSet 607

Loading Data Sets from a File 609

Creating a Data Set Programmatically 611

Loading Data Sets from a Database 613

Loading a DataTable with a DataReader 619

Master-Details DataSets 621

Retrieving Data with Stored Procedures 623

Updating the Database Using Data Sets 624

Handling Concurrency 628

Updating with Data Sets and Stored Procedures 632

Searching Data Sets 637

Merging Data from Multiple Data Sets 639

Working with Data Views 641

Working with Transactions 643

Scoping Transactions with System.Transactions 647

Client-Side Transactions 650

Data Set and Data Adapter Events 651

Reading Data into Business Objects 654

XML Data Access 658

Working with the XmlDataDocument Class 659

Working with the XPathDocument Class 663

Loading Data into an XPathDocument 664

Querying XML Data 665

Navigating an XML Document 667

Where Are We? 670

Index 671



Preface

Untitled Document When I first started discussing this book with the editors at Addison-Wesley, I was a little skeptical. My gut reaction was, "Will anyone need a whole book focused on data binding?" I mean, Windows Forms is just GUI stuff, right? You drag this, you drop that, you hook up a few event handlers, and you move on to build the rest of your enterprise application--all the middle-tier goo that ties your head in knots.

As I thought more about it, I realized that a significant percentage of the work that people do in Windows Forms applications is centered around data binding, and most of the problems that developers encounter are related to getting data binding scenarios to work correctly. Add to that the multitude of new capabilities in Windows Forms 2.0 and Visual Studio 2005 related to data binding, and I quickly became convinced that this book would be a good idea. Hopefully you will agree after you have finished reading it.

Data binding is a powerful capability that has finally matured in Windows Forms 2.0 through the capabilities in the .NET Framework classes, combined with the rich designer support provided by Visual Studio 2005. By using data binding properly, you can save yourself from writing a lot of unnecessary code, provide your users a rich interactive experience for working with data that functions well, and produce code that is easy to maintain. To get it working correctly across a variety of use cases, you need to know more than how to set a few properties on controls. You need to understand what is going on under the hood, especially if you want to support complex scenarios that require going beyond the basic capabilities of the data binding components in the .NET Framework.

Due to the growth of smart client architecture, Windows Forms applications are becoming more prominent in business systems which I discuss in Chapter 1. Web browser-based applications leave a lot to be desired; they cannot support many of today's common scenarios. They do not harness the capabilities of the client machine, and they are constrained by the request-response model of browser-based applications and the connectivity issues that surround them. So the importance of being able to code complex data application scenarios in Windows Forms is growing, and luckily the capabilities in .NET services are rapidly maturing to keep pace.

Who Should Read This Book?

The primary audience for this book is intermediate to advanced Windows Forms developers who want to learn about the new data binding features in Windows Forms 2.0 and refine their coding practices for data-bound applications. This book dives deep into advanced features of the data binding mechanisms in Windows Forms, data-bound controls, working with data sources, and creating custom data-bound objects and collections. However, if you are a beginning Windows Forms developer, this book will also help you quickly learn how to support data binding. Many of the features in Windows Forms 2.0 take developers through wizards and designer features that are helfpul for beginning programmers and you will learn about those features in this book. In addition, Appendices C and D are geared for beginner programmers to get up to speed on the basics of Windows Forms and data access. If you spend a significant amount of time working with data in Windows Forms applications, then this book is for you.

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 the DataSet class from a conceptual discussion of data sets. Short code listings are presented inline within the text using a different monspace font.

Longer listings use a similar font, but are identified with listing numbers, for example, "Listing 4-1." Within code listings, I sometimes bold particularly relevant portions of the code, especially to highlight "evolving code." When I removed details that aren't relevant to a discussion, you'll see a comment with ellipses (//...). This means that more code is needed to complete the example or more code generated by the designer exists, but you don't need it to understand the concept. On occasion, I will add explanatory comments to designer code to show context.

I use a conversational tone to discuss the kinds of objects you deal with in data binding scenarios, for example, when describing the DataSet class in this book. However, much of the time when I am talking about data sets I am not talking about an instance of a DataSet class, but of an instance of a derived typed DataSet class. Although it would still be technically correct to talk about that class as a DataSet, since it "is a" DataSet through inheritance, I find it annoying when too many words are called out as a code artifacts. So, when something really is a code artifact and can only be discussed correctly in that context, it's set in the monoface font. I favor the terms data set, data table, and table adapter when discussing concepts surrounding those types of objects, and reserve DataSet, DataTable, and CustomersTableAdapter for when I am talking about a specific class type or instance, and the capabilities defined by that code artifact.

Discussing components and controls can also be confusing, depending on how precise you want to be with your language. Technically, all controls in Windows Forms are components, because the Control class derives from the Component class. Many of the concepts surrounding data binding apply to both components, such as the BindingSource component discussed in depth in this book, and controls, such as a DataGridView control. Unfortunately, many people think of components as nonvisual objects that are used by your form, and controls as objects that have a visual rendering on your forms. To avoid having to say controls and components ad nauseam, when I discuss a concept that applies to both nonvisual components and controls, I simply say components. So when you see components, think "this applies to controls as well, because they inherit from components."

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, and if they do affect the code or concepts, I will provide corrections through the Web site for the book (www.softinsight.com/databindingbook), as well as updated code that will run on Visual Studio 2005 once it is released.

If you plan to run the samples available on the book's Web site, or the walkthroughs and code listings in the book, you will need Visual Studio 2005 installed on your machine, and you will need access to a SQL Server 2000 or 2005 database server on which the Northwind sample database has been installed. Additionally, you will need to have permissions on that database to create new databases for some of the samples.

There are multiple versions of Visual Studio 2005 to choose from. All of the features discussed in this book work even in the Express versions of Visual Studio 2005, which are free. You can develop all of the samples in this book in Visual C# 2005 Express or Visual Basic 2005 Express with SQL Server 2005 Express, but because Express versions of Visual Studio don't support data connections using server paths (they only support file path-based connections to SQL Express databases), you will have to create the sample databases and data in SQL Express, and then alter the connection strings and the way you set up connections based in Express.

The samples and scripts included in the book assume you are working on a machine with a standard, professional, or enterprise version of Visual Studio 2005 installed, along with a default instance of either SQL Server 2000 or 2005 on your local machine. To run the samples without that configuration will require modifying the connection string settings for all of the samples that run against a database. The modifications needed are discussed on the book's Web site, and the differences in connection strings are highlighted in many places in the sample code.

Additionally, Northwind does not ship with SQL Server 2005, but is available as a separate installable download that will work with SQL Server 2005 from MSDN Downloads at www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46A0-8DA2-EEBC53A68034&displaylang=en. The download provides scripts and MDF files that can be attached to SQL Server 2005 or that can be used with SQL Server 2005 Express.

Choice of Language

I chose to write this book in C#. The download code is available in both C# and Visual Basic. It is a fact of life that there will continue to be a mix of C# and Visual Basic available in articles, books, and code samples for a long time to come. Even though I prefer C# myself, I am not a language bigot and feel Visual Basic is a solid choice for developers who have a strong background in earlier versions of Visual Basic.

I firmly believe that to be an effective .NET developer, you need to be able to read code from either language, even if you spend most of your time with one. If you are not already comfortable reading C# code, I encourage you to use this opportunity to get comfortable reading it. It will expand your horizons in terms of the amount of reference material that is available to you, it may help you in your job, and it will give you bragging rights over the many silly and close-minded C# developers who can't read Visual Basic.

Coding Standards

Yes, I have one, and you should too. It is as simple as that, but unfortunately not done nearly enough by development organizations. Coding standards are an important tool in making sure that code is bug free, but they are even more essential for making sure that your code base is maintainable. Code written by one developer on your team should look like the code written by all the other developers so that it can be maintained and extended if necessary. Code reviews go hand in hand with your coding standard, and are also something that should be a regular part of your development process.

We have an excellent coding standard at my company, IDesign, Inc., that can be downloaded from our site at www.idesign.net. You can use our coding standard as is, or you can use it to develop your own coding standard. Our standard includes a lot of information that goes beyond simple syntax; it has a lot of best practices for .NET development and design.

For the code presented in this book, I used our coding standard for naming member variables, properties, methods, and event handlers. Any member of a class, whether just a variable or a control on a form, is given a prefix of m_ and Pascal Casing is used for the rest of the name. This is different from the Microsoft standard (which varies somewhat across different product teams), and that is okay. You can use whatever standard you want, as long as you are consistent. I won't go into the arguments and justifications of our coding standard here, but I want to shortcircuit any complaints or e-mails that might result.

You will see code snippets where this convention is not followed (when I am discussing designer-generated code), because the naming conventions generated by the designer differ from our coding standard. So when discussing the raw code generated by the designer, I will demonstrate the way they generate the code; when I am writing code or focusing on other aspects of the code, I will rename the things generated by the designer to comply with IDesign coding standard.

Code First vs. Design Features First

One of the hardest decisions I had to make when writing this book was in the order in which to present the concepts: Should I start by discussing code that you can write by hand to get things working in an application, or should I start by walking through all the different combinations of design features in Visual Studio that will write the code for you?

You can get a lot of data binding done through a combination of drag-and-drop interactions in the Visual Studio designer and by setting properties for objects on a form in the Properties window and other windows. When coding production applications, the Visual Studio designer is where you will start 90% of the time. Ultimately, those interactions are just having designer write the code so that you don't have to. This allows applications to be written much faster, and helps figure out how to get data binding scenarios working even if you don't really understand the code that is being generated.

If this book's goal were to cover more introductory level concepts across a wider scope of topics, then sticking to the designer with a little bit of code explanation would be sufficient. However, my goal is to provide a deep technical tutorial on all aspects of Windows Forms data binding for developers who want to tackle complex scenarios that go beyond the designers. Whenever you thoroughly want to understand what is going on, you need to really think about things at the code level, not at the level where the designer, wizards, and windows in Visual Studio are doing magic things for you.

As a result, I chose to tackle things from a code-first perspective. As you progress through the book, for most common scenarios there are ways to get the Visual Studio designers to write most or all of the code for you initially. But to maintain that code and to go beyond those common scenarios, you also need to be able to write that code by hand (if need be), and know what all the right pieces and parts are to hook together. The chapters are arranged to first introduce a concept and to show you the raw code that enables you to get that concept working. Then, if there's a corresponding designer way of getting that code written, that's covered next.

For example, Chapters 3 and 4 describes data binding mechanisms in Windows Forms and how to write the code to hook up controls to data sources. Then Chapter 5 shows how to use the Data Sources window to write a lot of that code for you. If you find it easier to learn by seeing things through the designer first and then unraveling the code, you might want to read the chapters and sections focused on the designer features first, and then return to previous sections to understand the code that was written on your behalf.

Northwind--The Database That Will Never Die

To show examples of data binding, you need some data to work with. One approach is to create new databases with new data in them to use in examples. While that may provide more interesting data for the samples, it has the downside of requiring you to learn a new schema and to set up those data sources on your machine to try out the demos. Because most interesting data usually belongs to someone, to avoid having to worry about copyrights and permissions to use the data, I created some sample databases for a few simple examples, but most of the examples use the tried-and-true Northwind database that is installed as part of the samples for SQL Server 2000 with a typical install. Also, through some downloadable scripts from Microsoft, you can get a Northwind instance installed on SQL Server 2005 or SQL Express 2005 as well. See the book's Web site for detailed instructions on how to do that.

Although many people are bored with Northwind (I count myself in that crowd), it does have the advantage of familiarity, and it is ubiquitously available and can be added easily as long as you have SQL Server. If you are already familiar with Northwind, you know about the Customers, Orders, and Order Details tables; if you're not, you can learn this fairly simple schema easily.

Overview of the Book

This book starts with some background in peripheral concepts surrounding data binding: how data bound Windows Forms applications fit into the bigger picture of distributed application architecture, particularly smart clients. It then dives quickly into the new data binding features in Windows Forms 2.0 and more advanced topics. The following is an overview of each chapter.

Chapter 1, Building Data Bound Applications with Windows Forms, introduces the concepts of data binding, along with a quick walkthrough sample using the designer to generate a data binding application. The data application architecture lays the groundwork for the other pieces to create a rich and robust data application.

Chapter 2, Working with Typed Data Sets and Table Adapters, shows how to use the new Visual Studio 2005 typed data set designer to generate most of the data access code needed in applications through simple drag-and-drop and wizard operations in the designer. It discusses the benefits of typed data sets, how to create and use them, and how to create and use typed table adapters to fill and update those data sets. It also covers how to use table adapters to perform ad hoc and custom queries.

Chapter 3, Introduction to Windows Forms Data Binding, starts delving into coding mechanisms in Windows Forms for data binding. It demonstrates how to perform simple and complex binding of data to controls, and introduces BindingSource--one of the most important data binding tools available in .NET 2.0.

Chapter 4, Binding Controls to Data Sources, builds on Chapter 3, further peeling back the layers on the use of the BindingSource component, and includes detailed coverage of using the Binding object for simple binding with automatic formatting and for handling binding events.

Chapter 5, Generate Bound Controls with the Visual Studio Designer, introduces the designer features for generating data binding code: drag-and-drop operations, wizards, and property grid interactions. It covers the Data Sources window in detail and the associated wizards.

Chapter 6, Presenting Data with the DataGridView Control, provides in-depth coverage of the DataGridView control, a rich tabular control for Windows Forms that is new in .NET 2.0. The chapter steps through basic usage as well as advanced scenarios, and describes customizing the content of cells, implementing cell-oriented grids, handling grid events, as well as many other features of the grid.

Chapter 7, Data Binding Interfaces, discusses the many interfaces involved in making the data binding process work, and shows you which interfaces you need to implement when and what is involved. This chapter will help cement your understanding of the real mechanisms that drive data binding.

Chapter 8, Implementing Custom Data Bound Controls, shows how to implement custom controls in Windows Forms for rendering data and what is required at the control level to use the data binding interfaces exposed by data collections and objects. It also discusses additional things to consider when creating data bound controls.

Chapter 9, Implementing Custom Data Bound Business Objects and Collections, covers how to create custom business objects and collections that you can use in data binding. It discusses implementing appropriate interfaces, and shows samples and how they get used. It provides detailed coverage of the BindingList generic class, which makes creating custom collections of data objects a snap.

Chapter 10, Validation and Error Handling, describes validation mechanisms in Windows Forms and how to properly harness those mechanisms. It discusses error handling at the form and data binding levels, along with strategies for managing concurrency violations.

Appendix A, Data Binding in ASP.NET 2.0, gives a quick introduction to ASP.NET data binding for developers who will have to write both Windows and Web applications.

Appendix B, WinFX Data Binding, looks at the data binding mechanisms in WinFX, the next generation presentation subsystem for Windows, so you can compare it to Windows Forms Data Binding.

Appendix C, Programming Windows Forms Applications, introduces the fundamentals of building Windows Forms applications. Written for beginning Windows Forms programmers, it will make the rest of the applications in the book understandable. It is not intended to be a comprehensive lesson on all other aspects of Windows Forms programming, just the essentials.

Appendix D, Data Access with ADO.NET, is a comprehensive overview of performing data access with ADO.NET. It covers many concepts, including retrieving and updating data with data sets and data readers, working with stored procedures, and managing transactions, as well as how to work with XML as a data source in .NET.

Sample Download Code and Updates

Upon publication, you will be able to download all of the sample code used in this book at www.softinsight.com/databindingbook. I will also post any changes, corrections, and updates relevant to the book at that location, and will post instructions on how to modify the sample code to run on the Express versions of Visual Studio and SQL Server 2005.

Foreword

Download the Foreword file related to this title.

Index

Download the Index file related to this title.

Updates

Submit Errata

More Information

Unlimited one-month access with your purchase
Free Safari Membership