In my application I want to select row in dataGrid1 that, in column "Order", have value actually stored in textBox. How can I select row programmaticaly (there won't be two rows with same number)?
Name your DataGrid so that the code in the code behind can access it. In the textbox subscribe to the KeyUp
or LostFocus
events and find the object which matches what was put in the textbox.
Example List Contains Orders with a unique OrderId
Xaml
<DataGrid AutoGenerateColumns="True"
Name="myGrid"
ItemsSource="{Binding Orders}"/>
<TextBox x:Name="tbSelection"
KeyUp="tbSelection_LostFocus"/>
Codebehind
private void tbSelection_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(tbSelection.Text) == false)
{
int userOrderId;
if (int.TryParse(tbSelection.Text, out userOrderId))
{
var orders = myGrid.ItemsSource as List<Order>;
var order = orders.FirstOrDefault(ord => ord.OrderId == userOrderId);
if (order != null)
myGrid.SelectedItem = order;
else
myGrid.SelectedIndex = -1; // Default to nothing.
}
else
myGrid.SelectedIndex = -1; // Default to nothing.
}
}
Result
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.