Anya
Anya

Reputation: 105

Datagrid that is bound to DataTable does not display any rows that are added dynamically to DataTable

I Have dataGrid like that:

public class myGrid : DataGrid {

    DataTable Table = new DataTable();

    public myGrid()
    {
    }

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        List<string> List = new List<string> { "Size1", "Size2", "Price", "Price2", "Note"} ;
        foreach (string Name in List)
        {
            Table.Columns.Add(Name);

            DataGridTextColumn c = new DataGridTextColumn();
            c.Header = Name;
            c.Binding = new Binding(Table.Columns[Name].ColumnName);
            this.Columns.Add(c);
        }

        DataColumn[] keys = new DataColumn[1];
        keys[0] = Table.Columns["PRICE"];
        Table.PrimaryKey = keys;

        this.DataContext = Table;
    }



    public void AddRow(object[] Values)
    {
            Table.LoadDataRow(Values, true);

    }

}

After AddRow is called, Table does have a row, but myGrid doesn't. What am i doing wrong?

Thanks!

Upvotes: 0

Views: 802

Answers (2)

kristianp
kristianp

Reputation: 5905

Make Table a public property:

private DataTable m_Table

public DataTable Table
{
    get { return this.m_Table; }

    protected set { m_Table = value; NotifyPropertyChanged("Table"); }
}

You also need to call NotifyPropertyChanged("Table"); in your AddRow function.

Upvotes: 0

Ankesh
Ankesh

Reputation: 4895

Using MVVM will be a better apporach.... you will not even nedd to inherit the grid for this purpose...

View Model

class MyViewModel:INotifyPropertyChanged
{
     private ObservableColleciton<string> myCollection;

   public MyViewModel()
   {
      //FunctiontoFillCollection()
   }

   public ObservableColleciton<string> MyCollection
   {
         get { return myCollection;}
         set
         {
             mycolletion = value;
             // i am leaving implemenation of INotifyPropertyChanged on you 
             // google it.. :)
             OnpropertyChanged("MyCollection");
         }
   }
}

View.Xaml

<DataGrid ItemsSource={Binding Path=MyCollection}>
 <!--Make Columns according to you-->
</DataGrid>

View.xaml.cs

/// <summary>
/// Interaction logic for MainView.xaml
/// </summary>
public partial class MainView : Window
{
    public MainView()
    {
        InitializeComponent();
        this.DataContext = new MyViewModel();
    }
}

Now add ne thing to MyColleciton and it will be reflectied in the View automatically.....

read some article fro MVVm implemenation for better understanding...

Upvotes: 2

Related Questions