19

我想为 datagrid 中的选定单元格获取值,请任何人告诉我该怎么做。我使用 SelectedCell 更改事件,我该怎么做?

dataGrid1.CurrentCell
4

14 回答 14

17

请参阅 MSDN 上的DataGrid 类页面。从该页面:

选择

默认情况下,当用户单击 DataGrid 中的单元格时,会选择整行,并且用户可以选择多行。您可以设置SelectionMode属性以指定用户是否可以选择单元格、整行或两者。设置 SelectionUnit 属性以指定是否可以选择多行或单元格,或者只能选择单行或单元格。

您可以获取有关从SelectedCells属性中选择的单元格的信息。您可以在 SelectedCellsChanged 事件的SelectedCellsChangedEventArgs中获取有关其选择已更改的单元格的信息。调用 SelectAllCells 或 UnselectAllCells 方法以编程方式选择或取消选择所有单元格。有关详细信息,请参阅 DataGrid 控件中的默认键盘和鼠标行为。

我已经为你添加了相关属性的链接,但是我现在时间不够了,所以我希望你可以点击链接来获得你的解决方案。

于 2013-10-07T16:20:00.033 回答
17

如果您只选择一个单元格,则像这样获取选定的单元格内容

var cellInfo = dataGrid1.SelectedCells[0];

var content = cellInfo.Column.GetCellContent(cellInfo.Item);

这里的内容将是您选择的单元格值

如果您选择多个单元格,那么您可以这样做

var cellInfos = dataGrid1.SelectedCells;

var list1 = new List<string>();

foreach (DataGridCellInfo cellInfo in cellInfos)
{
    if (cellInfo.IsValid)
    {
        //GetCellContent returns FrameworkElement
        var content= cellInfo.Column.GetCellContent(cellInfo.Item); 

        //Need to add the extra lines of code below to get desired output

        //get the datacontext from FrameworkElement and typecast to DataRowView
        var row = (DataRowView)content.DataContext;

        //ItemArray returns an object array with single element
        object[] obj = row.Row.ItemArray;

        //store the obj array in a list or Arraylist for later use
        list1.Add(obj[0].ToString());
    }
}
于 2013-10-07T18:15:22.927 回答
16

当我遇到这个问题时,我是这样处理的:我创建了一个DataRowView,抓住了列索引,然后在行的ItemArray

DataRowView dataRow = (DataRowView)dataGrid1.SelectedItem;
int index = dataGrid1.CurrentCell.Column.DisplayIndex;
string cellValue = dataRow.Row.ItemArray[index].ToString();
于 2013-12-11T21:48:21.907 回答
8

我正在将 Rushi 的解决方案扩展到以下(这为我解决了难题)

var cellInfo = Grid1.SelectedCells[0];
var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text;
于 2017-12-03T07:16:59.793 回答
5

如果SelectionUnit="Cell"试试这个:

    string cellValue = GetSelectedCellValue();

在哪里:

    public string GetSelectedCellValue()
    {
        DataGridCellInfo cellInfo = MyDataGrid.SelectedCells[0];
        if (cellInfo == null) return null;

        DataGridBoundColumn column = cellInfo.Column as DataGridBoundColumn;
        if (column == null) return null;

        FrameworkElement element = new FrameworkElement() { DataContext = cellInfo.Item };
        BindingOperations.SetBinding(element, TagProperty, column.Binding);

        return element.Tag.ToString();
    }

好像不应该那么复杂,我知道...

编辑:这似乎不适用于DataGridTemplateColumn类型列。如果您的行由自定义类组成并且您已分配排序成员路径,您也可以尝试此操作:

    public string GetSelectedCellValue()
    {
        DataGridCellInfo cells = MyDataGrid.SelectedCells[0];

        YourRowClass item = cells.Item as YourRowClass;
        string columnName = cells.Column.SortMemberPath;

        if (item == null || columnName == null) return null;

        object result = item.GetType().GetProperty(columnName).GetValue(item, null);

        if (result == null) return null;

        return result.ToString();
    }
于 2015-09-23T17:15:40.447 回答
2
//Xaml Code
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Date, Converter={StaticResource    dateconverter}, Mode=OneWay}" Header="Date" Width="100"/>
<DataGridTextColumn Binding="{Binding Path=Prescription}" Header="Prescription" Width="900"/>
</DataGrid.Columns>

//C# Code
 DataRowView row = (DataRowView)grid1.SelectedItem;
 MessageBox.Show(row["Prescription"].toString() + " " + row["Date"].toString());

由于 WPF 在 DataGrids 中提供绑定,这应该是相当透明的。但是,仅当您使用了 SQLDataAdapter 并提供了到 DataGridColumns 的绑定路径时,以下方法才有效。例如。假设上面的数据网格名为 grid1,它的自动生成列设置为 false,并使用绑定将列名绑定到标题。在这种情况下,我们使用“DataRowView”类型的“行”变量并将选定的行存储在其中。现在,使用您的绑定路径,并引用所选行的各个列。希望这可以帮助!干杯!

PS:如果 SelectionUnit = 'Row' 则有效

于 2017-02-02T22:47:17.373 回答
2

好的,在进行了逆向工程和一些反射的小精灵之后,可以SelectedCells(在任何时候)执行此操作以从一个到多个选定单元格中获取所有(无论是在一行还是多行上选择)数据:

MessageBox.Show(

string.Join(", ", myGrid.SelectedCells
                        .Select(cl => cl.Item.GetType()
                                             .GetProperty(cl.Column.SortMemberPath)
                                             .GetValue(cl.Item, null)))

               );

我仅在文本(字符串)字段上尝试了此操作,尽管 DateTime 字段应返回值 initial ToString()。另请注意,SortMemberPath这与Header应该始终提供适当的属性来反映不一样。

<DataGrid ItemsSource="{Binding MyData}"                      
          AutoGenerateColumns="True"
          Name="myGrid"
          IsReadOnly="True"
          SelectionUnit="Cell"
          SelectionMode="Extended">
于 2017-09-05T15:18:57.250 回答
1

这些是可用于从所选行中获取值的 2 种方法

    /// <summary>
    /// Take a value from a the selected row of a DataGrid
    /// ATTENTION : The column's index is absolute : if the DataGrid is reorganized by the user,
    /// the index must change
    /// </summary>
    /// <param name="dGrid">The DataGrid where we take the value</param>
    /// <param name="columnIndex">The value's line index</param>
    /// <returns>The value contained in the selected line or an empty string if nothing is selected</returns>
    public static string getDataGridValueAt(DataGrid dGrid, int columnIndex)
    {
        if (dGrid.SelectedItem == null)
            return "";
        string str = dGrid.SelectedItem.ToString(); // Take the selected line
        str = str.Replace("}", "").Trim().Replace("{", "").Trim(); // Delete useless characters
        if (columnIndex < 0 || columnIndex >= str.Split(',').Length) // case where the index can't be used 
            return "";
        str = str.Split(',')[columnIndex].Trim();
        str = str.Split('=')[1].Trim();
        return str;
    }

    /// <summary>
    /// Take a value from a the selected row of a DataGrid
    /// </summary>
    /// <param name="dGrid">The DataGrid where we take the value.</param>
    /// <param name="columnName">The column's name of the searched value. Be careful, the parameter must be the same as the shown on the dataGrid</param>
    /// <returns>The value contained in the selected line or an empty string if nothing is selected or if the column doesn't exist</returns>
    public static string getDataGridValueAt(DataGrid dGrid, string columnName)
    {
        if (dGrid.SelectedItem == null)
            return "";
        for (int i = 0; i < columnName.Length; i++)
            if (columnName.ElementAt(i) == '_')
            {
                columnName = columnName.Insert(i, "_");
                i++;
            }
        string str = dGrid.SelectedItem.ToString(); // Get the selected Line
        str = str.Replace("}", "").Trim().Replace("{", "").Trim(); // Remove useless characters
        for (int i = 0; i < str.Split(',').Length; i++)
            if (str.Split(',')[i].Trim().Split('=')[0].Trim() == columnName) // Check if the searched column exists in the dataGrid.
                return str.Split(',')[i].Trim().Split('=')[1].Trim();
        return str;
    }
于 2015-06-11T08:39:50.913 回答
1

我为这个挣扎了很久!(使用 VB.NET)基本上你得到所选单元格的行索引和列索引,然后使用它来访问值。

Private Sub LineListDataGrid_SelectedCellsChanged(sender As Object, e As SelectedCellsChangedEventArgs) Handles LineListDataGrid.SelectedCellsChanged

    Dim colInd As Integer = LineListDataGrid.CurrentCell.Column.DisplayIndex

    Dim rowInd As Integer = LineListDataGrid.Items.IndexOf(LineListDataGrid.CurrentItem)

    Dim item As String

    Try
        item = LLDB.LineList.Rows(rowInd)(colInd)
    Catch
        Exit Sub
    End Try

End Sub

结束类

于 2016-09-14T17:55:56.603 回答
1

为我工作

object item = dgwLoadItems.SelectedItem;
string ID = (dgwLoadItems.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
MessageBox.Show(ID);
于 2020-02-29T16:15:25.797 回答
0

您也可以使用此功能。

 public static void GetGridSelectedView(out string tuid, ref DataGrid dataGrid,string Column)
    {
        try
        {
            // grid selected row values
            var item = dataGrid.SelectedItem as DataRowView;
            if (null == item) tuid = null;
            if (item.DataView.Count > 0)
            {
                tuid =  item.DataView[dataGrid.SelectedIndex][Column].ToString().Trim();
            }
            else { tuid = null; }
        }
        catch (Exception exc) { System.Windows.MessageBox.Show(exc.Message); tuid = null; }
    }
于 2018-08-08T12:20:41.833 回答
0

我处于这种情况..发现了这个:

int ColumnIndex = DataGrid.CurrentColumn.DisplayIndex;
TextBlock CellContent = DataGrid.SelectedCells[ColumnIndex].Column.GetCellContent(DataGrid.SelectedItem);

并确保处理自定义列的模板

于 2019-08-18T04:13:32.930 回答
0

我是愚蠢的找到解决方案...

对我来说(VB):

 Dim string= Datagrid.SelectedCells(0).Item(0).ToString
于 2021-01-28T15:50:51.793 回答
0

Mohamed RT 的想法是正确的,它对我有用。唯一似乎缺少的是对 TextBlock 的显式强制转换。通过获取数据网格的 CurrentColumn.DisplayIndex,您可以定义您希望提取值的确切单元格。当用户重新排列列时,这也有效。这是我的代码:

int columnIndex = yourDataGrid.CurrentColumn.DisplayIndex;
TextBlock targetCell = (TextBlock)yourDataGrid.SelectedCells[columnIndex].Column.GetCellContent(yourDataGrid.SelectedItem);

并提取 TextBlock 的值:

MessageBox.Show("Target cell value is: " + targetCell.Text);

在我阅读的所有答案中,这似乎是最简单、最可靠的。非常感谢穆罕默德!

于 2021-10-13T19:40:12.683 回答