Obter o item da linha seleccionado no DataGrid WPF
tenho um DataGrid
, ligado à tabela de bases de Dados, preciso de obter o conteúdo da linha seleccionada no DataGrid, por exemplo, quero mostrar em MessageBox
o conteúdo da linha seleccionada.
Exemplo de DataGrid
:
Se eu seleccionar a segunda fila, o meu MessageBox
tem de mostrar algo como: 646 Jim Biology
.
11 answers
Poderá usar a propriedade SelectedItem para obter o objecto seleccionado de momento, que poderá então lançar no tipo correcto. Por exemplo, se o seu DataGrid estiver ligado a uma colecção de objectos do cliente, poderá fazer isto:
Customer customer = (Customer)myDataGrid.SelectedItem;
Em alternativa, pode ligar o SelectedItem à sua classe de origem ou ao ViewModel.
<Grid DataContext="MyViewModel">
<DataGrid ItemsSource="{Binding Path=Customers}"
SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>
Se estiver a usar o padrão MVVM, poderá ligar uma propriedade SelectedRecord
do seu VM com SelectedItem
do DataGrid, desta forma terá sempre o SelectedValue
no seu VM.
Caso contrário, deve utilizar a propriedade SelectedIndex
do DataGrid.
public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row) yield return row;
}
}
private void DataGrid_Details_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
var row_list = GetDataGridRows(DataGrid_Details);
foreach (DataGridRow single_row in row_lis)
{
if (single_row.IsSelected == true)
{
MessageBox.Show("the row no."+single_row .GetIndex ().ToString ()+ " is selected!");
}
}
}
catch { }
}
Isto é bastante simples nesta dg DataGrid e a classe de itens é povoada em datagrid e listblock1 é uma Moldura Básica.
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
var row_list = (Item)dg.SelectedItem;
listblock1.Content = "You Selected: " + row_list.FirstName + " " + row_list.LastName;
}
catch { }
}
public class Item
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Também podes:
DataRowView row = dataGrid.SelectedItem as DataRowView;
MessageBox.Show(row.Row.ItemArray[1].ToString());
private void DataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
if (DataGrid1.SelectedItem != null)
{
if (DataGrid1.SelectedItem is YouCustomClass)
{
var row = (YouCustomClass)DataGrid1.SelectedItem;
if (row != null)
{
// Do something...
// ButtonSaveData.IsEnabled = true;
// LabelName.Content = row.Name;
}
}
}
}
catch (Exception)
{
}
}
private void Fetching_Record_Grid_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
{
IInputElement element = e.MouseDevice.DirectlyOver;
if (element != null && element is FrameworkElement)
{
if (((FrameworkElement)element).Parent is DataGridCell)
{
var grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
{
//var rowView = grid.SelectedItem as DataRowView;
try
{
Station station = (Station)grid.SelectedItem;
id_txt.Text = station.StationID.Trim() ;
description_txt.Text = station.Description.Trim();
}
catch
{
}
}
}
}
}
Use a sua classe de modelos para obter os valores das linhas seleccionados a partir do datagrid como,
XDocument xmlDoc = XDocument.Load(filepath);
if (tablet_DG.SelectedValue == null)
{
MessageBox.Show("select any record from list..!", "select atleast one record", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
}
else
{
try
{
string tabletID = "";
/*here i have used my model class named as TabletMode*/
var row_list = (TabletModel)tablet_DG.SelectedItem;
tabletID= row_list.TabletID;
var items = from item in xmlDoc.Descendants("Tablet")
where item.Element("TabletID").Value == tabletID
select item;
foreach (var item in items)
{
item.SetElementValue("Instance",row_list.Instance);
item.SetElementValue("Database",row_list.Database);
}
xmlDoc.Save(filepath);
MessageBox.Show("Details Updated..!"
+ Environment.NewLine + "TabletId: " +row_list.TabletID + Environment.NewLine
+ "Instance:" + row_list.Instance + Environment.NewLine + "Database:" + row_list.Database, "", MessageBoxButton.YesNoCancel, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
}
Se eu seleccionar a segunda linha -
Dim jason As DataRowView
jason = dg1.SelectedItem
noteText.Text = jason.Item(0).ToString()
O texto não será 646. Isto é VB, mas tu percebes.
@Kritox responda com MVVM
<DataGrid
Grid.Column="1"
Grid.Row="1"
Margin="10" Grid.RowSpan="2"
ItemsSource="{Binding Data_Table}"
SelectedItem="{Binding Select_Request, Mode=TwoWay}" SelectionChanged="DataGrid_SelectionChanged"/>//The binding
#region View Model
private DataRowView select_request;
public DataRowView Select_Request
{
get { return select_request; }
set
{
select_request = value;
OnPropertyChanged("Select_Request"); //INotifyPropertyChange
OnSelect_RequestChange();//do stuff
}
}