Hello All,
One approach I've tried to solve my problem of needing to be able to dynamically add columns to a databound xamDataGrid is to bind to a .NET DataTable. At startup, I hard-code some data into the DataTable. Then I provide a button which, when clicked, is supposed to add a new column and put random numbers in the new column. I then unbind and rebind the xamDataGrid. Oddly, I see only the original columns. My newly-added column does not show up. Here's the code:
Window1.xaml.cs:
using System;
using System.Windows;
namespace XamDataGridBoundToDataTable
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
m_myDataGrid.DataSource = MyDataTable.Instance.Rows;
}
private void m_addColumnButton_Click(object sender, RoutedEventArgs e)
{
int ColNum = MyDataTable.Instance.Columns.Count + 1;
string columnName = string.Format("Column {0}", ColNum);
MyDataTable.Instance.Columns.Add(columnName, typeof(int));
MyDataTable.Instance.Rows[0][columnName] = m_rand.Next(100);
MyDataTable.Instance.Rows[1][columnName] = m_rand.Next(100);
m_myDataGrid.DataSource = null;
m_myDataGrid.FieldLayouts.Clear();
m_myDataGrid.DataSource = MyDataTable.Instance.Rows;
}
private readonly Random m_rand = new Random();
}
}
App.xaml.cs:
using System.Windows;
namespace XamDataGridBoundToDataTable
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void HandleStartup(object sender, StartupEventArgs e)
{
MyDataTable.Instance.Columns.Add("Column 1", typeof(int));
MyDataTable.Instance.Columns.Add("Column 2", typeof(int));
MyDataTable.Instance.Columns.Add("Column 3", typeof(int));
MyDataTable.Instance.Rows.Add(new object [] {243, null, 158});
MyDataTable.Instance.Rows.Add(new object[] {17, 42, 144});
}
}
}
MyDataTable.cs:
using System.Data;
namespace XamDataGridBoundToDataTable
{
class MyDataTable : DataTable
{
static MyDataTable()
{
Instance = new MyDataTable();
}
public static MyDataTable Instance { get; private set; }
}
}
Can anybody fathom a reason why I'm still seeing only the original columns even after unbinding and rebinding?
Thanks, Dave