Developer .NET UPDATE--Data Binding--February 20, 2004

The SelectedIndexChanged event can fire unexpectedly in a ComboBox when data binding is involved. Here’s how to fix this problem.

ITPro Today Contributors

February 19, 2004

7 Min Read
ITPro Today logo in a gray background | ITPro Today

Developer .NET UPDATE—brought to you by SQL Server Magazine

http://sqlmag.com

This Issue Sponsored By

WIN A HARLEY MOTORCYCLE

http://www.devconnections.com

In This Issue

Developer .NET Perspectives

  • Dealing with Data Binding

  • New and Improved

  • Create J2EE Applications Within Visual Studio .NET

  • Developer .NET Perspectives

by Marquis Howard, [email protected]

  • Dealing with Data Binding

  • In "Handling Events that Fire Unexpectedly" (http://www.winnetmag.com/windows/article/articleid/41717/41717.html), I discussed how events fire somewhat unexpectedly for a ComboBox when data binding is involved. At the core of this problem are differences in how the ComboBox behaves, depending on whether data is bound or loaded into the control.

    I also showed you how to add items to the ComboBox's Items collection both ways: through the DataSource property (data binding) and through the Items.Add method (data loading). As you witnessed, the DataSource method causes two unexpected events to fire. So, what's causing the unexpected events to fire and how can you limit their impact?

    The first unexpected event fires because when Visual Studio .NET creates the comboBox1_SelectedIndexChanged method for you, it places the event-handler code inside the InitializeComponent method, which Visual Studio .NET also generates for you. You can find the following line within the generated code, which is, by default, collapsed:this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);

    This code ensures the handler is set up before the FormLoad method gets called. The result is that the FormLoad method fires the event when you set the ComboBox's DataSource property. When Visual Studio .NET adds the data to the ComboBox behind the scenes, an event initially fires because you've changed the array of elements.

    The second unexpected event fires for a different reason. Instead of the initial selection being -1 (which represents no selection), the first item is automatically selected, which results in the event being fired. You can see the difference in these two firings by watching the ComboBox's Text property value change in the debugger.

    So what are the options if you want data binding to behave more like the behavior that occurs when you use the Items.Add method? You have two options, and neither is very clean. The first option is to move the generated line of code out of the form's InitializeComponent method. If you don't set the event until after the ComboBox loads, the event won't fire. However, you now have a new problem: You've selected the first item in your ComboBox but you aren't executing the code associated with that selection. In addition, this solution presumes you're loading your ComboBox only in conjunction with the form loading; if you need to reload your ComboBox, this solution doesn't work.

    A better solution is to create a form-level Boolean variable that's named something like "m_bLoading." You set this variable to true before the call to bind a new array of data, then reset it to false after the ComboBox loads. In the SelectedIndexChanged method, you must check to see whether the variable is true before you proceed to your custom code. To implement this solution, change the SelectedIndexChanged method so that it looks similar to

if(!m_bLoading)

{

MessageBox.Show(this.comboBox1.Text);

}

This solution isn't perfect, though. The form will still behave differently because the first item in the ComboBox will still be selected by default. Thus, in addition to using the form-level variable, you need to assign the ComboBox's SelectedIndex to -1 after the ComboBox's DataSource property is set. The trick is to assign the-1 value before you indicate that loading is complete (i.e., set m_bLoading to false). Here's an example of the code that the FormLoad method would contain:

string[] sDataArray = new string[] {"one","two","three"};

this.m_bLoading = true;

this.comboBox1.DataSource = sDataArray;

this.comboBox1.SelectedIndex = -1;

this.m_bLoading = false;

The result is that your ComboBox's first selection will be blank, just as if you had used the Items.Add method. Because the SelectedIndex is -1 when the first item is selected, the event will fire and life is good.

If data binding is more trouble to code correctly than using the Items.Add method, what's the advantage of using data binding? Data binding provides a quick way to render data. However, be aware that data binding actually binds all the source data. For this reason, you should never bind a DataReader to a control. The binding carries the DataReader's open database connection, which is inefficient.

However, suppose that you have a table containing an array of items from which the user can select, and behind the scenes, you want to reference other data associated with each of those items. With data binding, you can keep the entire association in memory as a unit. That way, you can reference other columns and bind to other controls without needing to reference another variable or return to the database. When you bind other controls to the same data source as the ComboBox, you receive an added bonus: When SelectedIndex is changed, in essence, a new row in the data table is selected and the data in the other bound controls will immediately be updated and displayed by way of data binding.

When binding to a data table, keep in mind that the table might have unreferenced columns, which you're now keeping in memory. If the columns are memory hogs, they can make a noticeable performance impact on a device such as a Pocket PC. When you're working with data binding, you need to make sure that you're not consuming too many valuable resources.

Sponsor: WIN A HARLEY MOTORCYCLE

Dev Connections conference and expo will be held April 18 - 21. Back by popular demand are concurrently running events Microsoft ASP.NET Connections, Visual Studio Connections, and SQL Server Magazine Connections. Details about workshops, sessions, and speakers are online, including the exclusive Microsoft Day on "Yukon" and "Whidbey". Save $200, receive access to all three conferences for one price, and get a chance to win a Harley motorcycle. Go online or call 800-438-6720 or 203-268-3204.

http://www.devconnections.com

Announcements
(brought to you by SQL Server Magazine)

  • 360-degree SQL Server Resource

  • Visit the SQL Server Magazine Web site and access a library of valuable SQL Server tools. Take advantage of the search box and navigation toolbars to access new articles, active forums, archived articles, associated code, and more! The site features columns by such experts as Brian Moran and Itzik Ben-Gan. Click here:

http://www.sqlmag.com

  • SqlJunkies Has What Developers Need

  • SqlJunkies is your online community resource for original tutorial and how-to articles for developing applications with SQL Server 2000 and Yukon; peer-to-peer help and networking through discussion forums and newsgroups; technology tips and pointers from expert bloggers; and the latest in SQL Server-related events and news.

http://www.SqlJunkies.com

Events Central
(A complete Web and live events directory brought to you by Windows & .NET Magazine: http://www.winnetmag.com/events )

  • SQL New Web Seminar--Realizing the Return on Active Directory

  • Join Mark Minasi and Indy Chakrabarti for a free Web seminar and discover how to maximize the return on your Active Directory investments and cut the cost of security exposures with secure task delegation, centralized auditing, and Group Policy management. Register now and receive NetIQ's free "Securing Access to Active Directory-A Layered Security Approach" white paper.

http://www.winnetmag.com/seminars/activedirectoryroi

New and Improved
by Shauna Rumbaugh, [email protected]

  • Create J2EE Applications Within Visual Studio .NET

  • Mainsoft released Visual MainWin for the J2EE Platform, an application-development program that lets developers create Java 2 Enterprise Edition (J2EE) applications and Web services within Visual Studio .NET. Visual MainWin for J2EE compiles Microsoft intermediate language (MSIL) source code into Java bytecode. Developers can develop, run, debug, and deploy code within Visual Studio .NET and manage and deploy the Visual MainWin application as any standard J2EE application. Features include drag-and-drop programming, integrated dynamic Help, runtime libraries, the ability to import Java components, and support for Visual Basic .NET and C#. For pricing or to try a free trial version, contact Mainsoft at 800-624-6946 or on the Web.

http://www.mainsoft.com

Sponsored Links

Quest Software, Inc.

Database Contention Affecting SQL Server Performance? Download White Paper.

http://www.quest.com/landing/sqlmag_link1.asp

Innovartis Ltd

Auditable, Repeatable, Reversible team SQL code? Meet DB Ghost.

http://www.dbghost.com

Contact Us

  • About Developer .NET Perspectives -- [email protected]

  • About the newsletter -- [email protected]

  • About technical questions -- http://www.sqlmag.com/forums

  • About product news -- [email protected]

  • About your subscription -- [email protected]

  • About sponsoring an UPDATE -- contact Kate Silvertooth ([email protected])

  • This email newsletter is brought to you by Windows & .NET Magazine,the leading publication for IT professionals deploying Windows andrelated technologies. Subscribe today.

http://www.winnetmag.com/sub.cfm?code=wswi201x1z

View the Windows & .NET Magazine Privacy policy at

http://www.winnetmag.com/aboutus/index.cfm?action=privacy

Windows & .NET Magazine a division of Penton Media, Inc.
221 East 29th Street, Loveland, CO 80538
Attention: Customer Service Department

Copyright 2004, Penton Media, Inc. All Rights Reserved.

Read more about:

ITPro Today
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like