C# – How to bind controls to the DataGridView

cdata-bindingwinforms

I'm new to .NET, so please be patient with me 😉

On my Windows Form, I have a DataGridView that is bound to a data source. Since my grid is read-only, I have a set of controls (textbox, checkbox, etc.) outside the grid that will be used to edit the data.

I want the controls to be binded to the currently selected row in the grid. Currently, if I set the DataBindings of the controls to the same data source as the grid, only the first record is showned even if I move the record pointer in the grid.

What am I missing?

Environment: Windows Form, C#, Visual Studio 2008.

Best Answer

to keep this completely within Visual Studio's databinding environment, you can use two BindingSources, one for the DataGridView and another for your detail controls. This is very similar to the example found here:

http://msdn.microsoft.com/en-us/library/y8c0cxey.aspx

But, instead of using a detail table you're using your own controls to show the details. These controls can still be databound to the 2nd BindingSource.

Alternatively, just handle the SelectionChanged event on your DataGridView and write code to manually update the values of your controls. This 2nd approach is a little more lightweight and will probably perform slightly better.

Hope this helps!

Adam