C# DataGridView get selected Row / Column value

时间:2016-02-12 20:36:49

标签: c# wpf datagridview

I am trying to get the Value of the selected Row and a specific Column. I already tryed some ideas from stackoverflow, but nothing worked yet. If i use this code:

import pandas as pd

df = pd.DataFrame( {"A": [7001, 8001, 9001]} )
print df
      A
0  7001
1  8001
2  9001

equiv = {1:[7001, 8001], 2: [9001]}

d = dict( (v,k) for k in equiv for v in equiv[k] )
print d
{7001: 1, 9001: 2, 8001: 1}

df["B"] = df["A"].map(d)
print df
      A  B
0  7001  1
1  8001  1
2  9001  2

I get this error:

An unhandled exception of type 'System.NullReferenceException' occurred in NLauncher.exe

Additional information:

Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.

My XAML:

string strid = "";
DataRowView rowview = DG1.SelectedItem as DataRowView;
strid = rowview.Row["Id"].ToString();
MessageBox.Show(strid);

My complete C# code: http://pastebin.com/WEHV2Z6e

All I want to get is the value of the column "ID" of the selected row.

3 个答案:

答案 0 :(得分:1)

If your RewriteEngine On RewriteCond %{REQUEST_FILENAME}.php -f RewriteCond %{REQUEST_URI} !/$ RewriteRule ^(.*)$ $1\.php ErrorDocument 404 /404.php is bound to SelecetdItem like this:

Property

For DataItem of DataGrid:

private DataGridItem selectedDG1;

    public DataGridItem SelectedDG1
    {
        get { return selectedDG1; }
        set { selectedDG1 = value; 
            UpdateProperty("SelectedDG1"); 
            }
    }

Then ID can be get as public class DataGridItem { public string name { get; set; } public int id { get; set; } } .

And code SelectedDG1.id is wrong. This will only work when System.Data.DataRowView rowview = DG1.SelectedItem as System.Data.DataRowView; is a ItemSource. If Datatable is a collection then:

ItemSource

Anyway you can suppress the exception by putting a Null check over the line: (Also your var selctedItem = DG1.SelectedItem as DataGridItem; if (selctedItem != null) { int value = selctedItem.id; } is bound to 'id' and you are trying to retrive 'Id' that also can cause null exception)

DataGridColumn

答案 1 :(得分:0)

You are probably getting an NullReferenceException because your cast

List.ContainsAny(Text.SplitAny("This is a test string", " "), {"dog","string","bark"})

is invalid and returning null. That means that whatever type DG1.SelectedItem is, it cannot be cast to the type "DataRowView".

For accessing the ID itself, Kylo Ren's answer is probably the best way to approach it.

Edit: Because rowView is null, you are getting a NullReferenceException when trying to access the Row:

DataRowView rowview = DG1.SelectedItem as DataRowView;

答案 2 :(得分:0)

有一个简单的方法可以解决这个问题。

代替使用;

DataRowView rowview = DG1.SelectedItem as DataRowView;

使用;

dynamic rowView = DG1.SelectedItem;

之后;

strid = rowview.Id.ToString();