1

I have difficulty in extracting data from datagrid. Since I was using selectionchange event on datagrid. I managed to get the selected row and column index. But I couldn't find any properties to get the exact data from the datagrid or datagridrow or selectedcells. Hope to get some advice from you guys, cheers.

8
  • 1
    Please be more specific - why can't you use ItemsSource of your grid at the first place?
    – user572559
    Nov 7, 2011 at 16:09
  • item source is a list, whose elements are contents for comboboxcolumn of datagrid. So I want to get the user's selected value.
    – Joshua H.
    Nov 7, 2011 at 16:13
  • I think one way is to get a "snapshot" of the datagrid when datagrid selectionchanged. But I couldn't find a property for it. Another way?(i'm not sure) is through binding. I want use textbinding the comboboxcolumn to a string and get the string when the selection changed. but i'm not sure how to do that.
    – Joshua H.
    Nov 7, 2011 at 16:16
  • 1
    Cast your grid's ItemsSource to a collection and get the item by index.
    – user572559
    Nov 7, 2011 at 16:21
  • But can i know which one is selected?
    – Joshua H.
    Nov 7, 2011 at 16:24

2 Answers 2

2

Bind your DataGrid to an ItemsSource containing your data, and then your SelectedItem will be the item in your ItemsSource.

You had a comment above of using ComboBoxes, so here's an example:

<DataGrid ItemsSource="{Binding MyData}" AutoGernateColumns="False">
    <DataGrid.Columns>
        <DataGridComboBoxColumn ItemsSource="{Binding Path=DataContext.ComboBoxOptions, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
                                DisplayMemberPath="Name"
                                SelectedValuePath="Id"
                                SelectedValueBinding="OptionId" />
    </DataGrid.Columns>
</DataGrid>

The DataContext for your DataGrid would contain

ObservableCollection<SomeItem> MyData { get; set; }
ObservableCollection<Option> ComboBoxOptions{ get; set; }

The SomeItem class would have a property of OptionId, and the Option class would have an Id and Name field.

In this example, when you select an item in the DataGrid the DataGrid.SelectedItem would contain the SomeItem

Remember, in WPF your Data (DataContext) is your application, and your UI elements like ComboBoxes, TextBoxes, DataGrids, etc are all just a pretty interface to let the user interact with your Data

0

In your MouseDoubleClick Event , use the dataGrid1.SelectedIteam as Object.

The code should be like somewhat like following :

    private void dataGrid1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        edit(this.dataGrid1.SelectedItem as YourObject);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.