【问题标题】:How to fill DataGrid with DataTable content in UWP c#如何在 UWP c# 中用 DataTable 内容填充 DataGrid
【发布时间】:2019-05-12 19:14:24
【问题描述】:

我正在创建一个 UWP 应用并尝试使用包含来自我的数据库的数据的 DataTable 填充我的 DataGrid,但没有成功。 我已经搜索了解决方案,但无法摆脱错误。

XAML 代码:

<StackPanel>
    <Button Content="Fill DataGrid" Click="Button_Click"/>
    <controls:DataGrid x:Name="dataGrid"
                       Margin="30"
                       AutoGenerateColumns="True">
    </controls:DataGrid>
</StackPanel>

C#代码:

    private static DataTable GetDataTable()
    {
        DataTable dt = new DataTable();

        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("FirstName", typeof(string));
        dt.Columns.Add("LastName", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        dt.Columns.Add("City", typeof(string));

        for (int i = 0; i < 10; i++)
            dt.Rows.Add(i, "text", "text", "text", "text");

        return dt;
    }

    private  void Button_Click(object sender, RoutedEventArgs e)
    {
        DataTable dt = GetDataTable();
        dataGrid.ItemsSource = dt.DefaultView; 
    }

这个错误20次(表有10个条目)

Error: BindingExpression path error: 'Item' property not found on 'System.Data.DataRowView'. BindingExpression: Path='Item' DataItem='System.Data.DataRowView'; target element is 'Windows.UI.Xaml.Controls.TextBlock' (Name='null'); target property is 'Text' (type 'String')

当我将 ItemSource 与 DataContext 交换时:

 dataGrid.DataContext = dt.DefaultView; 

我没有收到任何错误,但我也没有以任何方式更改 dataGrid。

我尝试在 Windows 窗体中使用 DataGridView 做同样的事情,我已经成功了:

private void button_Click(object sender, EventArgs e)
{
    DataTable dt = GetDataTableFromDatabase();
    dataGridView1.DataSource = dt;
}

我明白了,所以它不是数据库或 DataTable 的问题。

我已经设法通过使用 DataTable 中的实体创建一个列表并将它们作为源添加到 dataGrid 来实现解决方法,但问题是我有很多不同的 DataGrid,如果我能以某种方式会容易得多解决问题的方式类似于带有 dataGridView 的 windows 窗体中的示例。

感谢任何帮助。

【问题讨论】:

  • 我编辑了你的案例,但是,用上面的代码很难重现这个问题。你能分享一个小样本吗?
  • @NicoZhu-MSFT 我稍微编辑了代码,这个示例显示了相同的行为。

标签: c# datatable uwp datagrid


【解决方案1】:

感谢this 网站,我想通了。

    public static void FillDataGrid(DataTable table, DataGrid grid)
    {
        grid.Columns.Clear();
        grid.AutoGenerateColumns = false;
        for (int i = 0; i < table.Columns.Count; i++)
        {
            grid.Columns.Add(new DataGridTextColumn()
            {
                Header = table.Columns[i].ColumnName,
                Binding = new Binding { Path = new PropertyPath("[" + i.ToString() + "]") }
            });
        }

        var collection = new ObservableCollection<object>();
        foreach (DataRow row in table.Rows)
        {
            collection.Add(row.ItemArray);
        }

        grid.ItemsSource = collection;
    }

也许不是解决这个问题的最优雅的方法,但它确实有效,并且完全符合我的要求。

并且您必须将 dataGrid 属性“AutoGenerateColums”设置为“False”。这给我带来了很多问题。

【讨论】:

  • 你在 xaml 页面的哪里声明 ObservableCollection?我不能使用列项目模板,因为它一直说没有 ObservableCollection。对此进行了一些搜索,但在从代码隐藏绑定时,我还没有点击它来了解如何做到这一点。谢谢。
【解决方案2】:

我不知道这是一个更好的答案,但是当我发现这个问题时,我刚刚开始工作。我习惯了 Asp.Net,所以这是我想出的。

在 xaml 页面上(或使用)xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"

nModel.Data.ListData = 类文件。

 public class ListData
{
    public string HashId { get; set; }
    public int SortOrder { get; set; }
    public string StrSortOrder { get; set; }
    public string DataPoint { get; set; }
    public string Rfid { get; set; }
    public string Description { get; set; }
    public string Attch { get; set; }
}

并在页面代码隐藏中:

   DataTable dt = new DataTable();
        dt = nModel.DataDAL.ListData.ListDataDataTable("30039");

        List<nModel.Data.ListData> dataList = new List<nModel.Data.ListData>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            nModel.Data.ListData ListData = new nModel.Data.ListData();
            ListData.StrSortOrder = dt.Rows[i]["SortOrder"].ToString();
            ListData.DataPoint = dt.Rows[i]["DataPoint"].ToString();
            ListData.Rfid = dt.Rows[i]["Rfid"].ToString();
            dataList.Add(ListData);
        }
       
        dataGrid.ItemsSource = dataList;

还有网格

<controls:DataGrid x:Name="dataGrid"
                       AutoGenerateColumns="False">
        <controls:DataGrid.Columns>
            <controls:DataGridTextColumn Header="Piece#"
                                         Binding="{Binding StrSortOrder}"/>
            <controls:DataGridTextColumn Header="SerialNo"
                                         Binding="{Binding DataPoint}"/>
            <controls:DataGridTextColumn Header="Rfid"
                                         Binding="{Binding Rfid}"/>
            
        </controls:DataGrid.Columns>
        </controls:DataGrid>

花几天时间学习 uwp 就很明显了,为什么没人用 DataTables。

GridView 和 ListView 控件与 Asp.Net 版本不同。甚至不清楚 DataGrid 控件是否是一个东西。当我回到这个问题并深入挖掘时,我有些沮丧。

谢谢你的提问...

【讨论】:

    猜你喜欢
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2013-03-05
    • 2018-02-15
    • 2014-06-20
    相关资源
    最近更新 更多