0

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");
    }
}
SpaghettiChef
  • 31
  • 1
  • 7

2 Answers2

0

I think it's easier to use a DataGrid. With it you can then do the following programmatically.

programmatically add column & rows to WPF Datagrid

Max
  • 68
  • 8
0

My data doesn't show up in dataGrid at all

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

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);
}
Nico Zhu
  • 32,367
  • 2
  • 15
  • 36