如何通过foreach循环访问DataGridView行值

时间:2016-12-02 22:29:08

标签: c# wpf for-loop foreach wpfdatagrid

我正在制作一个wpf应用程序,并在尝试迭代或循环遍历DataGrid时遇到问题。 我在stackoverflow上搜索了很多但是无法得到我的答案。

到目前为止,我所做的是:

1:XAML:

<Grid>
    <Grid Margin="10">
        <DataGrid Name="dgUsers" AutoGenerateColumns="False" Margin="0,0,0,138" RowDetailsVisibilityMode="Visible">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                <DataGridTextColumn Header="Birthday" Binding="{Binding Birthday}" />
            </DataGrid.Columns>

        </DataGrid>
    </Grid>
    <Button Height="49" VerticalAlignment="Bottom" Content="Get Data From GridView" HorizontalAlignment="Left" Width="160" RenderTransformOrigin="1.617,0.486" Margin="178,0,0,83" Click="Button_Click"></Button>
</Grid>

2:C#代码背后:

public MainWindow()
    {
        InitializeComponent();
        List<User> users = new List<User>();
        users.Add(new User() { Id = 1, Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new User() { Id = 2, Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
        users.Add(new User() { Id = 3, Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });

        dgUsers.ItemsSource = users;

    }
    public class User
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public DateTime Birthday { get; set; }


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


//Here I tried a lot of solutions but every time I got the same error.
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var row = GetDataGridRows(dgUsers);
        /// go through each row in the datagrid 
        foreach (DataGridRow r in row)
        {
            DataRowView rv = (DataRowView)r.Item;
            foreach (DataGridColumn column in dgUsers.Columns)
            {
                if (column.GetCellContent(r) is TextBlock)
                {
                    TextBlock cellContent = column.GetCellContent(r) as TextBlock;
                    MessageBox.Show(cellContent.Text);
                }
                else if (column.GetCellContent(r) is CheckBox)
                {
                    CheckBox chk = column.GetCellContent(r) as CheckBox;
                    MessageBox.Show(chk.IsChecked.ToString());
                }
            }
        } 
    }

得到的错误是:

this

请建议我如何通过任何循环(for或foreach)获取DataGrid行和列值的正确解决方案。

先谢谢。

0 个答案:

没有答案