简体   繁体   English

WPF DataGrid从文本框中选择带有值的行

[英]WPF DataGrid select row with value from textbox

In my application I want to select row in dataGrid1 that, in column "Order", have value actually stored in textBox. 在我的应用程序中,我想选择dataGrid1中在“订单”列中具有实际存储在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. 命名您的DataGrid,以便后面代码中的代码可以访问它。 In the textbox subscribe to the KeyUp or LostFocus events and find the object which matches what was put in the textbox. 在文本框中,订阅KeyUpLostFocus事件,然后找到与文本框中的内容匹配的对象。

Example List Contains Orders with a unique OrderId 示例列表包含具有唯一OrderId的订单

在此处输入图片说明

Xaml 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 结果

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM