zsharp
zsharp

Reputation: 13766

BindingContext and a Multiselected datagridview

Getting the current object with BindingContext is no problem but what do I do when I have selected many rows in the datagridview? How do I iterate through each object?

Upvotes: 2

Views: 1346

Answers (2)

Larry
Larry

Reputation: 18051

Assuming your DataGridView is bound to a BindingSource, using the DataMember property this way :

myDataGridView.DataSource = someBindingSource;
myDataGridView.DataMember = "SomeCollectionProperty";

Then you can retrieve the list of bound items behind your DataGridView:

IList dataBoundItems = 
          ((CurrencyManager)grid.BindingContext[grid.DataSource, grid.DataMember]).List;

You may also want to cast this list to an IEnumerable<T> using :

var myItems = dataBoundItems.OfType<myClass>();

Upvotes: 0

Bob Horn
Bob Horn

Reputation: 34335

This wasn't easy or fun. Binding multiple selected rows in the datagrid isn't supported by default. I use MultiSelectBehavior from Functional Fun:

http://blog.functionalfun.net/2009/02/how-to-databind-to-selecteditems.html

These are my notes to get it to work:

To get this to work, I did this:

Add this namespace definition to the view: xmlns:ff="clr-namespace:FunctionalFun.UI.Behaviours;assembly=MultiSelectBehavior"

Within the datagrid, add the last two lines shown here (ff:... and SelectionMode....): ff:MultiSelectorBehaviours.SynchronizedSelectedItems="{Binding SelectedTasks}" SelectionMode="Extended"

Note: In the view model, SelectedTasks cannot be null, even when first declared.

No:private ObservableCollection selectedTasks;

Yes: private ObservableCollection selectedTasks = new ObservableCollection();

And this is some actual code that works:

xmlns:ff="clr-namespace:FunctionalFun.UI.Behaviours;assembly=MultiSelectBehavior"

        <DataGrid Grid.Row="1" AutoGenerateColumns="False" IsReadOnly="True" HeadersVisibility="Column"
                  ItemsSource="{Binding SelectedApplicationServer.ApplicationsWithOverrideGroup}"
                  ff:MultiSelectorBehaviours.SynchronizedSelectedItems="{Binding SelectedApplicationsWithOverrideGroup}"
                  SelectionMode="Extended">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Path=Application.Name}" Header="Name" Width="150" />
                <DataGridTextColumn Binding="{Binding Path=Application.Version}" Header="Version" Width="100"/>
                <DataGridTextColumn Binding="{Binding Path=CustomVariableGroup.Name}" Header="Override Group" Width="*"/>
            </DataGrid.Columns>
        </DataGrid>

Hope it helps.

Edit: I simply added the Functional Fun code as a project within my solution, and then I referenced it within my view project:

enter image description here

enter image description here

Upvotes: 2

Related Questions