WPF Datagrid获取选定的单元格值

时间:2013-10-07 12:58:27

标签: c# wpf datagrid

我想在datagrid中获取所选单元格的值,请任何人告诉如何执行此操作。我使用了SelectedCell改变了事件,我怎么能这样做?

dataGrid1.CurrentCell

13 个答案:

答案 0 :(得分:14)

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

中使用了它
DataRowView dataRow = (DataRowView)dataGrid1.SelectedItem;
int index = dataGrid1.CurrentCell.Column.DisplayIndex;
string cellValue = dataRow.Row.ItemArray[index].ToString();

答案 1 :(得分:13)

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

  

<强>选择

     

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

     

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

我已经为您添加了相关属性的链接,但我现在已经没时间了,所以我希望您可以按照链接获取解决方案。

答案 2 :(得分:11)

如果您只选择一个单元格,那么就像这样选择单元格内容

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());
    }
}

答案 3 :(得分:4)

如果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();
    }

答案 4 :(得分: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并提供了DataGridColoumns的绑定路径,则以下方法才有效。例如。让我们说上面的datagrid名为grid1,它自动生成列设置为false,并使用绑定将列名绑定到Headers。在这种情况下,我们使用&#39;行&#39;变量类型&#39; DataRowView&#39;并将选定的行存储在其中。现在,使用绑定路径,并引用所选行的各个列。 希望这可以帮助!干杯!

PS:如果SelectionUnit =&#39;行&#39;

,则有效

答案 5 :(得分:2)

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

var cellInfo = Grid1.SelectedCells[0];
var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text;

答案 6 :(得分:1)

这两种方法可用于从所选行中获取值

    /// <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;
    }

答案 7 :(得分: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

结束班

答案 8 :(得分:1)

在进行逆向工程和反射的小小精灵之后,可以在SelectedCells(在任何时候)执行此操作以获得全部(无论在一行上选择或许多行)从一个到多个选定单元格的数据:

MessageBox.Show(

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

               );

我在文本(字符串)字段上尝试过此操作,但DateTime字段应该返回值ToString()。另请注意,SortMemberPathHeader不同,因此应始终提供适当的属性以反映出来。

<DataGrid ItemsSource="{Binding MyData}"                      
          AutoGenerateColumns="True"
          Name="myGrid"
          IsReadOnly="True"
          SelectionUnit="Cell"
          SelectionMode="Extended">

答案 9 :(得分: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; }
    }

答案 10 :(得分:0)

为我工作

object item = dgwLoadItems.SelectedItem;
string ID = (dgwLoadItems.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
MessageBox.Show(ID);

答案 11 :(得分:0)

我愚蠢地找不到解决方案...

对于我(VB):

 Dim string= Datagrid.SelectedCells(0).Item(0).ToString

答案 12 :(得分:-1)

我当时处于这种情况..并发现了这一点

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

并确保对待自定义列的模板