获取DataGrid WPF中的选定行项

时间:2010-10-12 10:17:26

标签: wpf datagrid selecteditem

我有DataGrid,绑定到数据库表,我需要在DataGrid中获取所选行的内容,例如,我想在所选行的MessageBox内容中显示

DataGrid的示例:

enter image description here

因此,如果我选择第二行,我的MessageBox必须显示如下内容: 646 Jim Biology

12 个答案:

答案 0 :(得分:123)

您可以使用SelectedItem属性获取当前选定的对象,然后可以将其转换为正确的类型。例如,如果您的DataGrid绑定到Customer个对象的集合,则可以执行此操作:

Customer customer = (Customer)myDataGrid.SelectedItem;

或者,您可以将SelectedItem绑定到源类或ViewModel

<Grid DataContext="MyViewModel">
    <DataGrid ItemsSource="{Binding Path=Customers}"
              SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>    

答案 1 :(得分:17)

如果您正在使用MVVM模式,则可以将VM的SelectedRecord属性与DataGrid的SelectedItem绑定,这样您在VM中始终拥有SelectedValue。 否则,您应该使用DataGrid的SelectedIndex属性。

答案 2 :(得分:12)

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 { }
}

答案 3 :(得分:4)

在这个DataGrid dg中这非常简单,并且在datagrid中填充了item类,而listblock1是一个基本框架。

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

答案 4 :(得分:4)

你也可以:

DataRowView row = dataGrid.SelectedItem as DataRowView;
MessageBox.Show(row.Row.ItemArray[1].ToString());

答案 5 :(得分:2)

好吧,我会为我提供类似的解决方案。

 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)
            {
            }
        }

答案 6 :(得分:1)

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
                {

                }
            }
        }
    }
}

答案 7 :(得分:1)

在我尝试了Fara的答案之后刚刚发现了这个,但它对我的项目没有用。只需从“数据源”窗口拖动该列,然后将其拖放到“标签”或“文本框”。

答案 8 :(得分:1)

使用您的Model类获取从datagrid中选择的行值,例如

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

答案 9 :(得分:0)

如果我选择第二行 -

 Dim jason As DataRowView


    jason = dg1.SelectedItem

    noteText.Text = jason.Item(0).ToString()

noteText将是646.这是VB,但你明白了。

答案 10 :(得分:0)

@Krytox用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
        }
     }

答案 11 :(得分:0)

这里有很多答案可能在特定的上下文中有效,但是我只是想获取所选行中第一个单元格的文本值。尽管这里接受的答案对我来说是最接近的答案,但仍然需要创建一个类型并将该行强制转换为该类型。我一直在寻找一个更简单的解决方案,这就是我想出的:

MessageBox.Show(((DataRowView)DataGrid.SelectedItem).Row[0].ToString());

这给了我所选行的第一列。希望这可以帮助其他人。