WPF: Read SelectedItem
from DataGrid with Dynamic As Anonymous Type
How to
evaluate an Coloumn Value in a WPF DataGrid.SelectedItem?
Task:
I want to
read out the value of a column from a data glauge in WPF. Unfortunately, the
evaluation of DataGrid.SelectedItem results in a line from the Type
<Anonymous Type> and if you convert the Row into DataGrid.SelectedItem in
DataRowView then as a result is always zero returned or the conversion of
Anonymus Type into DataRowView is Not possible
Problem
conversion SelectedItem
DataRowView row = ctlDataGrid.SelectedItem as DataRowView;
->returns null
|
Solution:
Super
Solution with C # dynamic.
You can use
the time time data type dynamic. This dynamic data type can be used freely for
runtime like var variant and you can simply query the columns or fields like a
property.
So simply
convert SelectedItem into dynamic and then dynamic the column as. Evaluate
column. This is easier than forming an array or List of the Type String.
dynamic row = ctlDataGrid.SelectedItem;
sName = row.Nachname;
|
Excerpt: Debug
The Debug
extract shows that in the DataGrid SelectedItem an array of strings results in
runtime.
The
SelectedItem is from Type <Anonymous Type>
|
Name
|
|
Value
|
Type
|
◢
|
ctlDataGrid.SelectedItem
|
|
{ Nachname = "Butzer", Maschine = "Drehbank
1", Schichtgruppe = "Schicht 2" }
|
<Anonymous
Type>
|
Code example
on evaluations des ausgewählten Elements in einem WPF DataGrid Selected Item
Private void CtlDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//----------< CtlDataGrid_SelectionChanged() >----------
string sName = "";
//--< get_DataGrid_SelectedItem >--
//* get DataGrid.SelectedItem as <Anonymus Type > into c#.dynamic
//* get Value of dynamic variable simply bei get as named property like dynamic_value.Field
if (ctlDataGrid.SelectedItem != null)
{
dynamic row = ctlDataGrid.SelectedItem;
sName = row.Nachname;
}
//--</ get_DataGrid_SelectedItem >--
//< insert button >
Button btn = new Button();
btn.Background = new SolidColorBrush(Colors.Red);
btn.Content = sName;
//#todo: Event drag drop einfügen
_srcPanel.Child = btn;
//</ insert button >
this.Close();
//----------</ CtlDataGrid_SelectionChanged() >----------
}
|