I am trying to get the selected row va开发者_开发技巧lue from a DataGrid in WPF, and it's proving to be very frustrating. It's simple in WinForms, though.
How can I get the selected or a specified single row value from a datagrid control in wpf?
I have used several snippets i've found online, and all of them give me the contents of the whole row, including the column names!
I have tried:
string value = dataGrid1.SelectedItems[0].ToString();
string value = dataGrid1.SelectedCells[dataGrid1.SelectedItems[0]].ToString();
I've looked on MSDN under the wpf controls section but can't see how I can get a row value anywhere.
All I keep getting back is:
{ OrderId = d#dfuzJRo , UserId = 56, OrderTotal = , Freight = , DeliveryStatus = , OrderStatus = Pending, TransactionId = , OrderDate = 16/08/2011 9:12:00 PM }
- which isn't what I'm after.
I would like to get the OrderId when I double-click on a Row.
My XAML is setup like:
<DataGrid AutoGenerateColumns="True" Name="dataGrid1" DataContext="{Binding}" ItemsSource="{Binding}" HorizontalGridLinesBrush="#4D0090FF" VerticalGridLinesBrush="#A30091FF" AlternatingRowBackground="#200098FF" BorderThickness="0" ClipToBounds="False" MouseDoubleClick="dataGrid1_MouseDoubleClick" Margin="0,25,0,0" VerticalAlignment="Stretch"></DataGrid>
And I am getting DB info successfully (based off of MSDN tutorial) like:
private void ViewOrders()
{
ObjectQuery<Order> orders = dEntities.Orders;
var query = from order in orders
orderby order.OrderStatus
select new
{
order.OrderId,
order.UserId,
order.OrderTotal,
order.Freight,
order.DeliveryStatus,
order.OrderStatus,
order.TransactionId,
order.OrderDate
};
dataGrid1.ItemsSource = query.ToList();
}
OK, the simple SelectedItem
or SelectedItems[0]
will give you the row. But your row is an anonymous type, that makes getting the OrderID
a little difficult.
The simple approach is to simply select the order
item and display that. Set up column definitions in the grid to select which properties to show.
The alternative is to define a class DisplayOrder
, and then change the Linq query:
select new DisplayOrder
{
order.OrderId,
...
};
In both cases, you can simply access SelectedItem.OrderID
from the grid.
var row = (DisplayOrder) datagrid1.SelectedItem; // or (Order)
int Id = row.OrderID;
精彩评论