获取DataGrid值

时间:2012-10-01 15:20:01

标签: c# wpf wpftoolkit

伙计我知道这已被回答了一百万次,但我如何从我从数据网格中选择的行中获取值?我已经尝试过,但没有运气。数据网格的数据绑定很好,我使用selectedCellsChanged事件,但那是我卡住的地方。

我的代码如下: -

XAML

    <Window x:Class="main.results"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="results" Height="500" Width="650">
        <Window.Resources>
            <DataTemplate x:Key="LocationsTemplate">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=CLIENTNAME}" />
                    <TextBlock Text=" | " />
                    <TextBlock Text="{Binding Path=POSTCODE}" />
                    <TextBlock Text=" | " />
                    <TextBlock Text="{Binding Path=CONTRACT NUMBER}" />
                </StackPanel>
            </DataTemplate>
        </Window.Resources>
        <Grid>
            <DataGrid AutoGenerateColumns="False" Height="125" HorizontalAlignment="Left" Margin="16,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="600" ItemsSource="{Binding}" HorizontalGridLinesBrush="#FF7907C1" VerticalGridLinesBrush="#FF7907C1" SelectionMode="Single" SelectedCellsChanged="dataGrid1_SelectedCellsChanged">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding CLIENTNAME}" Header="CLIENT NAME" />
                    <DataGridTextColumn Binding="{Binding CLIENTNAME}" Header="POSTCODE" />
                    <DataGridTextColumn Binding="{Binding CONTRACT NUMBER}" Header="CONTRACT NUMBER" />
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Window>

C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    using System.Data;
    using System.Data.SqlClient;
    using System.Data.Linq;
    using System.Data.SqlTypes;

    namespace main
    {
        /// <summary>
        /// Interaction logic for results.xaml
        /// </summary>
        public partial class results : Window
        {
            public results()
            {
                InitializeComponent();
            }

            private void dataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
            {
               **//HOW DO I GET THE VALUES FROM SELECTED ROW?**
            }        
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用var dr = (DataRowView)dataGrid1.SelectedItem;获取行

然后dr["columnName"];获取列的值