从 WPF Datagrid 中的选定行获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37776214/
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 13:50:45  来源:igfitidea点击:

Get value from selected row in WPF Datagrid

c#wpfdatagrid

提问by B.Pumpkin

I have a DataGrid in my WPF projects

我的 WPF 项目中有一个 DataGrid

enter image description here

在此处输入图片说明

As you can see i'm able to select a row. I've made a double click method where i get the selected row. i want get just the ID part of that row.
This is how my method looks like

如您所见,我可以选择一行。我做了一个双击方法,我得到了选定的行。我只想获取该行的 ID 部分。
这就是我的方法的样子

enter image description here

在此处输入图片说明

private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
{
    DataGridRow = sender as DataGridRow;
}

How to I just get the cell where I put the ID in it?

我如何才能获得将 ID 放入其中的单元格?

Many thanks in advance

提前谢谢了

采纳答案by itzmebibin

If you are showing both XAML and cs code then only we can find the proper solution. Now I am assuming that you are displaying the contents by using binding from an observable collection of any class type. So you can easily get the ID field by,

如果您同时显示 XAML 和 cs 代码,那么只有我们才能找到合适的解决方案。现在我假设您通过使用来自任何类类型的可观察集合的绑定来显示内容。因此,您可以通过以下方式轻松获取 ID 字段,

private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
{
    ClassName classObj = dataGridName.SelectedItem as ClassName;
    string id = classObj.ID;
}

回答by LuisEduardoSP

This is the code I used to get the ID of the double clicked row. I used an exploit of the double click (When you double click a row, you also select it). In my case, the column containing the id was the first (Row[0])

这是我用来获取双击行 ID 的代码。我使用了双击的漏洞(当你双击一行时,你也选择了它)。就我而言,包含 id 的列是第一个 (Row[0])

    private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
    {
        DataRowView dataRowView = (DataRowView)yourDataGridView.SelectedItem;
        int ID = Convert.ToInt32(dataRowView.Row[0]);
    }