---
title: "Winforms Data Binding Woes"
url: "https://osherove.com/blog/2003/6/14/winforms-data-binding-woes.md"
canonical: "https://osherove.com/blog/2003/6/14/winforms-data-binding-woes.html"
published: "2003-06-14T16:08:00"
updated: "2003-06-14T16:08:00"
tags: [".Net Original"]
author: "Roy Osherove"
description: "I recently needed to get into Data Binding in win forms. I’ve read several articles( 1 , 2 , 3 ) and came up with several conclusions/questions: 1. Win forms Data Binding is very cool and powerful Using The…"
usage: "Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page)."
license: "https://creativecommons.org/licenses/by/4.0/"
---

# Winforms Data Binding Woes

By Roy Osherove June 14, 2003 In [.Net Original](https://osherove.com/blog/category/net-original)

**Historical article** · Originally published June 14, 2003; technical details may be outdated.

I recently needed to get into  Data Binding in win forms. I’ve read several articles([1](http://msdn.microsoft.com/msdnmag/issues/02/02/cutting/default.aspx),[2](http://www.dnzone.com/ShowDetail.asp?NewsId=155),[3](http://www.akadia.com/services/dotnet_databinding.html)) and came up with several conclusions/questions: 

1.      Win forms Data Binding is very cool and powerful

Using The _BindingContext_ and _CurrencyManager_ lets you do some powerful in a very simple way.

2.      You can easily create a master-details page using two datagrids , and  dataset containing a parent and child tables and a DataRelation object

3.      You **cannot** easily create a master-details form if you want a control other than a DataGrid to represent your Parent Table.

##### _About item No.3_

So why can’t you, for example, just slap on a form a ListBox and a DataGrid and make the ListBox change what the DataGrid shows? The answer is pretty simple, although I never would have figured it out myself;

When you bind a _DataGrid_ to a relation in a dataset, the _DataGrid_ tries to find all the controls on the form that use that relation’s Parent Table as their **_DataMember_**. It then retrieves the _CurrencyManager_ Associated with those controls and creates Ad-Hoc Event Handlers to these to its “_CurrentChanged_” Event, thus allowing itself to react to the user moving between separate parent records.

Here’s the catch – A _ListBox_ or _ComboBox_ or _TreeView_ control dones not have a **_DataMember_** property so any DataGrid that is on the form will not react when the user moves to a different item on that control. Sad but true.

So what do you do? How do you still make the _DataGrid_ respond?

The short answer is that you have to manually set the _BindingManager_’s _Position_ property (Which tells the bound controls on the form what records they are currently watching). You need to retrieve the Current _Row_ in your ListBox and loop through the _BindingManager_ rows until you find it.

Yeah, totally ugly. I couldn’t figure out a different way. I’m almost **sure** I’m missing something here.

What I **did** manage to come up with is a helper class that has but one static method that does all the hard work for you.

With this class in place, you can call it like this on your control’s IndexChange event:

      private void listBox1\_SelectedIndexChanged(object sender, System.EventArgs e)

      {

            BindingManagerHelper.Synchronize(listBox1.SelectedItem,BindingContext,m\_ds,"MyParentTable","MyPKColumn");

      }

Here’s the code for the class:

public class BindingManagerHelper

{

      public static void Synchronize(object CurrentRowView,

                                          BindingContext bindContext,

                                          object DataSource,

                                          string DataMember,

                                          string PrimaryKeyName)

      {

            //retrieve the Binding Manager that relates to this Data source and this Data member

            BindingManagerBase bm = bindContext\[DataSource,DataMember\];

            DataRow row =null;

            //A bound listbox can hold a DataRowView object

            //but sometimes you might just have a DataRow object inside

            //your control's Tag property.

            //this allows you to send either one.

            if(CurrentRowView is DataRow)

            {row = (DataRow)CurrentRowView;     }

            if(CurrentRowView is DataRowView )

            {row = ((DataRowView)CurrentRowView).Row;}

            if(row\==null)

                  throw new NotSupportedException(

                              "This object is not suppoerted for this method");

            //Recover the value we will look for when looping

            //through the BindingContext, so we know when to stop

            string WantedValue = row\[PrimaryKeyName\].ToString();

            //Start looping from the first record

            bm.Position\=0;

            while(true)

            {

                  try

                  {

                        //Check whether the current row is the one we are looking for

                        DataRow data\=((DataRowView)bm.Current).Row;

                        if (data\[PrimaryKeyName\].ToString() == WantedValue)

                        {

                              break;

                        }

                  }

                  catch(Exception ex){}

                  //Stop looping if you get to the last record

                  if(bm.Position\==bm.Count\-1)

                        break;

                  //Advance the BindingContext to the next record

                  bm.Position++;

            }

      }          

}

If anyone has a better idea of how to overcome this problem, I’d sure like to know, because I have a distinct feeling this is not an optimal solution (especially if you consider that every time we advance the binding context by one, all the controls on the form refresh to display the new data (Consider having thousands of DataRows!).

What **does** make sense here is to derive from that ListBox or that TreeView and make a Data Bindable Control. This technique is very well documented in [Dino Esposito’s MSDN column from Feb’ 2002](http://msdn.microsoft.com/msdnmag/issues/02/02/cutting/default.aspx), but unfortunately, that solution does not fit the need here. What he shows there is reacting to a _CurrentChanged_ event in a custom control, and what we are trying to do here is to **generate** such an event. Even if I did create such a control, what way would I have to know the position of the DataRow that was just clicked on my control without resorting to looping?

Again – another mystery. Hopefully, I’ll get some feedback on this and have some news on the subject…

## More in .Net Original

[All posts in .Net Original](https://osherove.com/blog/category/net-original)

- Jun 16, 2003

    ### [Funny Behaviour](https://osherove.com/blog/2003/6/16/funny-behaviour.html)

- Jun 15, 2003

    ### [Data Binding Woes - A Simple Solution](https://osherove.com/blog/2003/6/15/data-binding-woes-a-simple-solution.html)

- Jun 13, 2003

    ### [About Reflector, Encoding, And an Article Error](https://osherove.com/blog/2003/6/13/about-reflector-encoding-and-an-article-error.html)

- Jun 12, 2003

    ### [AppDomains Reloaded](https://osherove.com/blog/2003/6/12/appdomains-reloaded.html)


---

## About the author

**Roy Osherove**: Senior Solutions Architect at AWS working on AI for production and AI-driven development; author of The Art of Unit Testing and Elastic Leadership, with about 20 years of consulting and training on unit testing, TDD, team leadership and continuous delivery.

### Sites

- [RobotPaper](https://robotpaper.ai/): This blog: AI patterns and anti-patterns, AI and coding agents, and engineering leadership.
- [osherove.com](https://osherove.com): Roy's personal site. Author of The Art of Unit Testing and Elastic Leadership; consulting and training on unit testing, TDD, team leadership and continuous delivery, plus about 20 years of blog posts.
- [The Art of Unit Testing](https://www.artofunittesting.com): The Art of Unit Testing, 3rd Edition (Manning): readable, maintainable, trustworthy unit tests, plus TDD workshops in C#, JavaScript, Java and Kotlin.
- [5whys.com](https://www.5whys.com): Roy's writing on software team leadership: self-organizing teams, surviving chaos, learning mode and the Elastic Leadership model.
- [Pipeline Driven](https://pipelinedriven.org): Continuous delivery and DevOps practices: build patterns, pipeline-friendly testing, DevOps metrics and enterprise DevOps.
- [Elastic Leadership](https://www.elasticleadership.com): Elastic Leadership, Roy's framework for software team leaders (survival, learning and self-organizing modes).

### Social

- X: https://x.com/royosherove
- LinkedIn: https://www.linkedin.com/in/osherove/

### Contact

- Contact form: https://forms.gle/jQSx5KoXvrVA1JCK7

### License

Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page). License: https://creativecommons.org/licenses/by/4.0/
