我的数据根本没有显示在 dataGrid 中 [英] My data doesn't show up in dataGrid at all

查看:22
本文介绍了我的数据根本没有显示在 dataGrid 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 dataGrid,我想通过按下按钮来添加行.但是当按下按钮时.在 dataGrid 中看不到任何数据.实际上.dataGrid 中没有任何可见的内容.我该如何解决这个问题?

I have a dataGrid that I want to add rows with a button press. But when the button is pressed. No data is seen in the dataGrid. In fact. Nothing is visible in dataGrid. How can I solve this issue?

 public sealed partial class MainPage : Page
{
    DataTable table = new DataTable();
    public MainPage()
    {
        this.InitializeComponent();
        table.Columns.Add("title", typeof(string));
        table.Columns.Add("message", typeof(string));
        noteList.AutoGenerateColumns = false;
        noteList.ItemsSource = table.DefaultView;
    }

    private void bNew_Click(object sender, RoutedEventArgs e)
    {
        table.Rows.Add("Hello", "Hi");
    }
}

推荐答案

我的数据根本没有显示在 dataGrid 中

My data doesn't show up in dataGrid at all

UWP DataGrid 没有直接将 ItemsSource 设置为 table.DefaultView,我们需要使用下面的方法来加载 DataTable.

UWP DataGrid does not set ItemsSource as table.DefaultView directly, we need use the following method to load DataTable.

private ObservableCollection<object> collection = new ObservableCollection<object>();
public void FillDataGrid(DataTable table, DataGrid grid)
{
    grid.Columns.Clear();
    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;
}

如果你想动态添加Row.请将其插入到集合中,如下所示.

If you want to add Row dynamically. Please insert it into collection like below.

private void Button_Click(object sender, RoutedEventArgs e)
{
    table.Rows.Add("Hello1", "Hi1");
    var last = table.Rows[table.Rows.Count - 1];
    collection.Add(last.ItemArray);
}

这篇关于我的数据根本没有显示在 dataGrid 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆