1

I am binding dictionary to my DataGrid. Now I want to get the selected row from the DataGrid. Here is what I tried till now.

Dictionary<int, string> dicKeyValue = new Dictionary<int, string>();

public MainWindow()
    {
        InitializeComponent();

        dataGrid.DataContext = dicKeyValue;

        dicKeyValue.Add(1, "INDIA");
        dicKeyValue.Add(2, "CHINA");
        dicKeyValue.Add(3, "AMERICA");
        dicKeyValue.Add(4, "RUSSIA");

    }

private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var sample = (sender as DataGrid).SelectedItem as ******
       // Here in the above line what should I write to get the values of selected row.

        if (sample != null)
        {

        }


    }

while debugging I tried this in the Immediate Window.....

((sender as DataGrid).SelectedItem)
{[8, SCAN]}
Key: 8
Value: "SCAN"
key: 8
value: "SCAN"

Now can you guys please help me how to access this...

My question may look similar to this , but in my question I want to know the correct type into which I can typecast the SelectedItem.

AJAY KUMAR
  • 77
  • 7
  • 1
    @Kartoffel In the link you provided, they bind it to the class, so it is possible to cast. But in my case I bind it to dictionary. So I am asking the correct type into which I can cast. I think both questions are different.... – AJAY KUMAR Jun 19 '17 at 09:44

2 Answers2

2

Dictionary<TKey, TValue> inherits ICollection<KeyValuePair<TKey, TValue>> so your item type should be KeyValuePair<int, string>. For casting purposes, you could use the Nullable<T>:

var item = dataGrid.SelectedItem as KeyValuePair<int, string>?;
if (item.HasValue) // use item.Value

However, it might be worth to use dataGrid.SelectedValuePath = "Key" and then refer to dataGrid.SelectedValue instead of SelectedItem.

grek40
  • 13,113
  • 1
  • 24
  • 50
  • as KeyValuePair is non-nullable value type I cannot use it in ** "((sender as DataGrid).SelectedItem as KeyValuePair)"** – AJAY KUMAR Jun 19 '17 at 09:35
  • @AJAYKUMAR then use a direct cast instead of `as`: `if (selectedItem is KeyValuePair) { var item = (KeyValuePair)selectedItem; }` – grek40 Jun 19 '17 at 09:37
  • @AJAYKUMAR I doubt it, as long as you only use if `HasValue` is true, there should be no NullReferenceException unless you fail somewhere else. – grek40 Jun 19 '17 at 09:50
  • Ya if we use 'HasValue' we wont get exception, that doesn't mean we will have value in it. It won't have the selectedRow values. That is what I mean to say.... – AJAY KUMAR Jun 19 '17 at 09:53
  • @AJAYKUMAR are you absolutely sure that you actually have an selected item at the point you are complaining about? Please check whether `dataGrid.SelectedItem` is null itself - then no cast can save you. Otherwise please inspect dataGrid.SelectedItem.GetType() to find the actual involved type which *should be* `KeyValuePair` – grek40 Jun 19 '17 at 09:55
  • When I tried in Immediate Window, it threw Null Reference Exception, but when I tried in code it worked perfectly. Thanks – AJAY KUMAR Jun 19 '17 at 10:05
2

This should work:

private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid dataGrid = sender as DataGrid;
    if (dataGrid.SelectedItem != null)
    {
        var sample = (KeyValuePair<int, string>)dataGrid.SelectedItem;
        int key = sample.Key;
        string value = sample.Value;
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Why did you edit my answer instead of voting it up? sample is a KeyValuePair with a Key and a Value... – mm8 Jun 19 '17 at 10:14
  • I'd suggest to rollback the edit. I think AJAY was working with a confusing mix of `KeyValuePair` and its `Nullable` when doing the edit. – grek40 Jun 19 '17 at 11:03
  • @grek40: Edit rollbacked. – mm8 Jun 19 '17 at 11:11
  • Now if you harmonize your usage of `dataGrid` vs `sender as DataGrid` I might actually like the answer :) – grek40 Jun 19 '17 at 11:19
  • @grek40: Done :) – mm8 Jun 19 '17 at 11:33
  • @mm8 In case of casting, if teh SelectedItem is null (when we clear the datagrid, SelectionChaged event will raise), the it will throw exception. If we use as keyword, then it will not. Check it once. – AJAY KUMAR Jun 20 '17 at 10:38
  • @grek40 check my above comment. I used as keyword. so it will convert to 'KeyValuePair' so to access the values we have to write 'sample.Value.Key' and 'sample.Value.Value' – AJAY KUMAR Jun 20 '17 at 10:40
  • 1
    That's why I check that the SelectedItem is not null before casting. Did you miss the `if (dataGrid.SelectedItem != null)` line? – mm8 Jun 20 '17 at 10:40