开发者

Adding Row to DataGrid Silverlight

I have a Datagrid which show data from a database. each time i load the data from my data vase the old data is earsed and the is replaced with the new data.

What i want is for the pervious row to remain and the new data to be appened to the end of the datagrid.

my code is as shown below :

public MainPage()
    {


        InitializeComponent();
       dataGrid1.Columns.Add(new DataGridTextColumn { Header = "Year", Binding = new System.Windows.Data.Binding("year") });
        dataGrid1.Columns.Add(new DataGridTextColumn { Header = "One", Binding = new System.Windows.Data.Binding("One") });
        dataGrid1.Columns.Add(new DataGridTextColumn { Header = "Two", Binding = new System.Windows.Data.Binding("Two") });
        dataGrid1.Columns.Add开发者_开发技巧(new DataGridTextColumn { Header = "Three", Binding = new System.Windows.Data.Binding("Three") });


    }

void client_DoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
    {            
        dataGrid1.ItemsSource = e.Result;
    }

how do i append the new data from the database rather than overwriting the data ?? .


One very simple and no-frills way to do it (because you don't appear to be using a regular MVVM approach), is to create a new list (IEnumerable) which unions both the old list and the new list, then assign it back to the ItemsSource property:

List<MyObjects> abc = new List<MyObjects>(dataGrid2.ItemsSource).Union(e.Result);
dataGrid2.ItemsSource = abc;

I've broken this on to two lines to make it easier to understand. If you were using a ViewModel, then the property that is bound to the DataGrid would be a List<>, and then you can just do an AddRange(e.Result) to that property, and due to the beauty of data binding (and notifying) it will automatically show up in your datagrid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜