C# WPF Datagrid 获取选定的单元格值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19225568/
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
WPF Datagrid Get Selected Cell Value
提问by Abdulsalam Elsharif
I want to get value for selected cell in datagrid , please anyone tell how to do this. i used SelectedCell changed event , how can i do that?
我想获取 datagrid 中选定单元格的值,请任何人告诉如何做到这一点。我使用了 SelectedCell 更改事件,我该怎么做?
dataGrid1.CurrentCell
采纳答案by Sheridan
Please refer to the DataGrid Classpage on MSDN. From that page:
请参阅MSDN 上的DataGrid Class页面。从该页面:
Selection
By default, the entire row is selected when a user clicks a cell in a DataGrid, and a user can select multiple rows. You can set the SelectionModeproperty to specify whether a user can select cells, full rows, or both. Set the SelectionUnit property to specify whether multiple rows or cells can be selected, or only single rows or cells.
You can get information about the cells that are selected from the SelectedCellsproperty. You can get information about cells for which selection has changed in the SelectedCellsChangedEventArgsof the SelectedCellsChanged event. Call the SelectAllCells or UnselectAllCells methods to programmatically select or unselect all cells. For more information, see Default Keyboard and Mouse Behavior in the DataGrid Control.
选择
默认情况下,当用户单击 DataGrid 中的单元格时会选择整行,并且用户可以选择多行。您可以设置SelectionMode属性来指定用户是否可以选择单元格、整行或两者。设置 SelectionUnit 属性以指定是可以选择多行或单元格,还是只能选择单行或单元格。
您可以获得有关从SelectedCells属性中选择的单元格的信息。您可以在 SelectedCellsChanged 事件的SelectedCellsChangedEventArgs中获取有关选择已更改的单元格的信息。调用 SelectAllCells 或 UnselectAllCells 方法以编程方式选择或取消选择所有单元格。有关详细信息,请参阅 DataGrid 控件中的默认键盘和鼠标行为。
I have added links to the relevant properties for you, but I'm out of time now, so I hope you can follow the links to get your solution.
我已经为您添加了相关属性的链接,但我现在没时间了,所以我希望您可以按照链接来获得您的解决方案。
回答by Rushi Soni
If you are selecting only one cell then get selected cell content like this
如果您只选择一个单元格,则像这样获取选定的单元格内容
var cellInfo = dataGrid1.SelectedCells[0];
var content = cellInfo.Column.GetCellContent(cellInfo.Item);
Here content will be your selected cells value
这里的内容将是您选择的单元格值
And if you are selecting multiple cells then you can do it like this
如果您要选择多个单元格,那么您可以这样做
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());
}
}
回答by Drew Sands
When I faced this problem, I approached it like this:
I created a DataRowView
, grabbed the column index, and then used that in the row's ItemArray
当我遇到这个问题时,我是这样处理的:我创建了一个DataRowView
,抓取了列索引,然后在行的索引中使用了它ItemArray
DataRowView dataRow = (DataRowView)dataGrid1.SelectedItem;
int index = dataGrid1.CurrentCell.Column.DisplayIndex;
string cellValue = dataRow.Row.ItemArray[index].ToString();
回答by Trikasus
These are 2 methods that can be used to take a value from the selected row
这些是可用于从所选行中获取值的 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;
}
回答by Charles Clayton
If SelectionUnit="Cell"
try this:
如果SelectionUnit="Cell"
试试这个:
string cellValue = GetSelectedCellValue();
Where:
在哪里:
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();
}
Seems like it shouldn't be that complicated, I know...
好像没那么复杂,我知道……
Edit:This doesn't seem to work on DataGridTemplateColumn
type columns. You could also try this if your rows are made up of a custom class and you've assigned a sort member path:
编辑:这似乎不适用于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();
}
回答by Thomas Bailey
I struggled with this one for a long time! (Using VB.NET) Basically you get the row index and column index of the selected cell, and then use that to access the value.
我与这个斗争了很长时间!(使用 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
End Class
结束类
回答by Ketan Dubey
//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());
As WPF provides binding in DataGrids, this should be rather transparent. However, the following method only works, if you have used SQLDataAdapter and provided a binding path to your DataGridColoumns. For eg. Let's say the above datagrid is named grid1, which has auto generate columns set to false, and is using binding to bind column names to Headers. In this case, we use the 'row' variable of type 'DataRowView' and store the selected row in it. Now, use your Binding Paths, and reference individual columns of the selected row. Hope this helps! Cheers!
由于 WPF 在 DataGrids 中提供绑定,这应该是相当透明的。但是,以下方法仅适用于,如果您使用了 SQLDataAdapter 并提供了到 DataGridColumns 的绑定路径。例如。假设上面的数据网格名为 grid1,它的自动生成列设置为 false,并使用绑定将列名绑定到标题。在这种情况下,我们使用“DataRowView”类型的“row”变量并将所选行存储在其中。现在,使用您的绑定路径,并引用所选行的各个列。希望这可以帮助!干杯!
PS: Works if SelectionUnit = 'Row'
PS:如果 SelectionUnit = 'Row' 有效
回答by ΩmegaMan
Ok after doing reverse engineering and a little pixie dust of reflection, one can do this operation on SelectedCells
(at any point) to get all(regardless of selected on one row or many rows) the data from one to many selected cells:
好的,在进行逆向工程和一点点反射后,可以对SelectedCells
(在任何时候)执行此操作以获取从一个到多个选定单元格中的所有(无论是在一行还是多行上选择)数据:
MessageBox.Show(
string.Join(", ", myGrid.SelectedCells
.Select(cl => cl.Item.GetType()
.GetProperty(cl.Column.SortMemberPath)
.GetValue(cl.Item, null)))
);
I tried this on text (string) fields only though a DateTime field should return a value the initiate ToString()
. Also note that SortMemberPath
is not the same as Header
so that should always provide the proper property to reflect off of.
我在文本(字符串)字段上尝试了这个,只是 DateTime 字段应该返回一个初始值ToString()
。另请注意,SortMemberPath
这与Header
应始终提供适当的属性进行反射不同。
<DataGrid ItemsSource="{Binding MyData}"
AutoGenerateColumns="True"
Name="myGrid"
IsReadOnly="True"
SelectionUnit="Cell"
SelectionMode="Extended">
回答by Rajesh Thampi
I'm extending the solution by Rushi to following (which solved the puzzle for me)
我正在将 Rushi 的解决方案扩展到以下(这为我解决了难题)
var cellInfo = Grid1.SelectedCells[0];
var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text;
回答by Arun kumar
you can also use this function.
您也可以使用此功能。
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; }
}