请帮助我,我试图从SelectionChangedEvent中的选定行获取Cell [0]的值。
我只是设法获得许多不同的Microsoft.Windows.Controls,并希望我错过了一些愚蠢的东西。
希望我能从这里得到一些帮助......
private void datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Microsoft.Windows.Controls.DataGrid _DataGrid = sender as Microsoft.Windows.Controls.DataGrid;
}
我希望它会像... ...
_DataGrid.SelectedCells[0].Value;
然而.Value不是一个选择......
非常感谢,这让我很生气! 丹
答案 0 :(得分:14)
代码少,而且有效。
private void datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex);
DataGridCell RowColumn = dataGrid.Columns[ColumnIndex].GetCellContent(row).Parent as DataGridCell;
string CellValue = ((TextBlock)RowColumn.Content).Text;
}
ColumnIndex是您想知道的列的索引。
答案 1 :(得分:8)
请检查以下代码是否适合您:
private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
if (e.AddedItems!=null && e.AddedItems.Count>0)
{
// find row for the first selected item
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(e.AddedItems[0]);
if (row != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
// find grid cell object for the cell with index 0
DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(0) as DataGridCell;
if (cell != null)
{
Console.WriteLine(((TextBlock)cell.Content).Text);
}
}
}
}
static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null) child = GetVisualChild<T>(v);
if (child != null) break;
}
return child;
}
希望这有帮助,尊重
答案 2 :(得分:3)
由于您使用&#34; SelectionChanged&#34;,您可以将发件人用作数据网格:
DataGrid dataGrid = sender as DataGrid;
DataRowView rowView = dataGrid.SelectedItem as DataRowView;
string myCellValue = rowView.Row[0].ToString(); /* 1st Column on selected Row */
我尝试了这里发布的答案并且很好,但在开始隐藏DataGrid中的列时给了我一些问题。即使隐藏列,这个也适合我。希望它也适合你。
答案 3 :(得分:2)
这将为您提供WPF中DataGrid中当前选定的行: -
DataRow dtr = ((System.Data.DataRowView)(DataGrid1.SelectedValue)).Row;
现在获取单元格值只需编写dtr[0]
,dtr["ID"]
等
答案 4 :(得分:1)
private void datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid _DataGrid = sender as DataGrid;
string strEID = _DataGrid.SelectedCells[0].Item.ToString();
}