从 wpf 检索 gridview 选定行中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16984374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:57:20  来源:igfitidea点击:

retrieve values in selected row of gridview from wpf

c#.netwpfvisual-studio-2010

提问by Freelancer

I am new with WPF.

我是 WPF 的新手。

I am trying to retireve values of selected row of gridview in respected text boxes.

我正在尝试在受尊重的文本框中停用 gridview 选定行的值。

In windows application, i use to do it like:

在 Windows 应用程序中,我习惯于这样做:

txtPartyCode=gv.SelectedRows[0].Cells[1].Value.ToString();

But i am confused, how to do it with WPF?

但我很困惑,如何用 WPF 做到这一点?

I tried:

我试过:

txtPartyCode.Text=gvCust.SelectedItem[0]

but, red tooltip is appearing below code : can not apply index with [] to an expression of type object.

但是,红色工具提示出现在代码下方: can not apply index with [] to an expression of type object.

Please help me. How to do it with WPF?

请帮我。如何用 WPF 做到这一点?

回答by JSJ

here i am confused what is your data type. which you are passing to the ItemsSource property of datagrid.

在这里我很困惑你的数据类型是什么。您将其传递给数据网格的 ItemsSource 属性。

if you are usnig DataTable and passing it to datagrid then the below code will work for you.

如果你是 usnig DataTable 并将它传递给 datagrid 那么下面的代码对你有用。

void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {                   
            DataRowView rowview = dataGrid1.SelectedItem as DataRowView;
            if (rowview != null)
            {
             textbox1.Text=  rowview.Row.ItemArray[0].ToString();
            }            
        }

and if you are using Typed object for the itemsSource property of DataGrid e.g List of Employees. then here what you can do.

如果您使用 Typed 对象作为 DataGrid 的 itemsSource 属性,例如员工列表。那么在这里你可以做什么。

 Employee emp  = dataGrid1.SelectedItem as Employee
if(emp !=null)
{
textBox1.Text =  emp.Name;
}

回答by apomene

 private void YourGridName_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {               
          string fc = null;                   
          foreach (var item in e.AddedCells)
           {                        
            fc =((System.Data.DataRowView(item.Item)).Row.ItemArray[0].ToString();
           }
         }

回答by NidhinSPradeep

You may try adding a handler for the DataGrid SelectionChanged Event, as follows:

您可以尝试为 DataGrid SelectionChanged 事件添加一个处理程序,如下所示:

private void dataGrid1_SelectionChanged(object sender, RoutedEventArgs e)
{
       DataRowView rowview = gv.SelectedItem as DataRowView;
       string textNeeded = rowview.Row[0].ToString();
}