【问题标题】:Why doesn't it show me the values in my DataGrid that I assign in the DataTable?为什么它不显示我在 DataTable 中分配的 DataGrid 中的值?
【发布时间】:2021-04-08 13:47:49
【问题描述】:

我最初在我的 DataGrid 中手动编写了标题,现在我想从 DataTable 中填充 DataGrid。我想这样做:

void fillingDataGrid()
    {
        DataTable dt = new DataTable();
        DataColumn id = new DataColumn("id", typeof(int));
        DataColumn name = new DataColumn("name", typeof(string));
        DataColumn ort = new DataColumn("ort", typeof(string));
        DataColumn alter = new DataColumn("alter", typeof(string));
        DataColumn land = new DataColumn("land", typeof(string));

        dt.Columns.Add(id);
        dt.Columns.Add(name);
        dt.Columns.Add(ort);
        dt.Columns.Add(alter);
        dt.Columns.Add(land);

        DataRow firstrow = dt.NewRow();
        firstrow[0] = 1;
        firstrow[1] = "Peter";
        firstrow[2] = "Berlin";
        firstrow[3] = "18";
        firstrow[4] = "Germany";

        DataRow secondrow = dt.NewRow();
        firstrow[0] = 2;
        firstrow[1] = "Karl";
        firstrow[2] = "Prag";
        firstrow[3] = "12";
        firstrow[4] = "Tschechien";

        dt.Rows.Add(firstrow);
        dt.Rows.Add(secondrow);

        gridd.ItemsSource = dt.DefaultView;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.fillingDataGrid();
    }

然而,问题是,如果我这样做,它不会正确输出,因为它看起来像这样:

为什么它不显示所有数据,我需要在 DataTable 上更改什么?

【问题讨论】:

  • 什么是gridd?事件处理是否正确连接?请参考minimal reproducible example
  • 我的数据网格的名称我给它命名为 gridd

标签: c# xaml datagrid


【解决方案1】:

改变这一行:

gridd.ItemsSource = dt.DefaultView;

收件人:

gridd.DataContext = dt.DefaultView;

【讨论】:

  • 那我什么都没花
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
  • 2019-09-20
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 2015-09-18
  • 2017-11-14
相关资源
最近更新 更多