[英]Issue to get selected row of datagrid in wpf
<Employees>
<Employee>
<EmpId>1</EmpId>
<Name>Sam</Name>
<Sex>Male</Sex>
</Employee>
<Employee>
<EmpId>2</EmpId>
<Name>Lucy</Name>
<Sex>Female</Sex>
</Employee>
</Employees>
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="0.8*"/>
<RowDefinition Height="0.05*"/>
</Grid.RowDefinitions>
<DataGrid x:Name="DgrdEmployeeDetails" Grid.Row="0" FontSize="14.667" FontWeight="Bold" RowHeight="60" ColumnHeaderHeight="60" RowHeaderWidth="40" ColumnWidth="*"/>
<StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Center">
<Button x:Name="BtnGetSelectedRow" Content="GetSelectedRow" Width="120" Height="50" Click="BtnGetSelectedRow_Click" />
</StackPanel>
</Grid>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
XDocument emplyeeDetails = XDocument.Load("Employees.xml");
var emplyees = from emp in emplyeeDetails.Descendants("Employee").Take(10)
orderby emp.Element("EmpId").Value ascending
select new
{
Id = emp.Element("EmpId").Value,
Name = emp.Element("Name").Value,
Sex = emp.Element("Sex").Value
};
DgrdEmployeeDetails.ItemsSource = emplyees.ToList();
}
private void BtnGetSelectedRow_Click(object sender, RoutedEventArgs e)
{
DataRowView dr= DgrdEmployeeDetails.SelectedItem as DataRowView;
}
when i click the GetSelectedRow button dr return null value 当我单击GetSelectedRow按钮dr返回空值
Null because you can`t cast a dynamic object to DataRowView. 空,因为您不能将动态对象投射到DataRowView。
var dr= DgrdEmployeeDetails.SelectedItem;
dr is an instance of dr是的实例
{
Id,
Name,
Sex
};
ObservableCollection<EmpData> _EmpDetail =
new ObservableCollection<EmpData>();
public ObservableCollection<EmpData> EmpDetail
{ get { return _EmpDetail; } }
public class EmpData
{
public int Id{ get; set; }
public string Sex{ get; set; }
public int name{ get; set; }
}
var emplyees = from emp in emplyeeDetails.Descendants("Employee").Take(10)
orderby emp.Element("EmpId").Value ascending
select new
{
Id = emp.Element("EmpId").Value,
Name = emp.Element("Name").Value,
Sex = emp.Element("Sex").Value
};
foreach (var Emp in emplyees )
{
_EmpDetail.Add(new EmpData
{
Id= Emp.Id,
Sex= Emp.Sex,
Name= Emp.Name
});
}
DgrdEmployeeDetails.ItemsSource = _EmpDetail;
private void BtnGetSelectedRow_Click(object sender, RoutedEventArgs e)
{
EmpData dr= DgrdEmployeeDetails.SelectedItem as EmpData;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.