views:

180

answers:

2

I'm trying to create a simple Silverlight application that involves parsing a CSV file and displaying the results in a DataGrid. I've configured my application to parse the CSV file to return a List<CSVTransaction> that contains properties with names: Date, Payee, Category, Memo, Inflow, Outflow.

The user clicks a button to select a file to parse, at which point I want the DataGrid object to be populated. I'm thinking I want to use data binding, but I can't seem to figure out how to get the data to show up in the grid.

My XAML for the DataGrid looks like this:

<data:DataGrid IsEnabled="False" x:Name="TransactionsPreview">
    <data:DataGrid.Columns>
        <data:DataGridTextColumn Header="Date"
                                 Binding="{Binding Date}" />
        <data:DataGridTextColumn Header="Payee" 
                                 Binding="{Binding Payee}"/>
        <data:DataGridTextColumn Header="Category"
                                 Binding="{Binding Category}"/>
        <data:DataGridTextColumn Header="Memo" 
                                 Binding="{Binding Memo}"/>
        <data:DataGridTextColumn Header="Inflow" 
                                 Binding="{Binding Inflow}"/>
        <data:DataGridTextColumn Header="Outflow" 
                                 Binding="{Binding Outflow}"/>
    </data:DataGrid.Columns>
</data:DataGrid>

The code-behind for the xaml.cs file looks like this:

    private void OpenCsvFile_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            CsvTransObject csvTO = new CsvTransObject.ParseCSV();
            //This returns a List<CsvTransaction> and passes it
            //to a method which is supposed to set the DataContext
            //for the DataGrid to be equal to the list.
            BindCsvTransactions(csvTO.CsvTransactions);                 
            TransactionsPreview.IsEnabled = true;
            MessageBox.Show("The CSV file has a valid header and has been loaded successfully.");
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }   
    }

    private void BindCsvTransactions(List<CsvTransaction> listYct)
    {
         TransactionsPreview.DataContext = listYct;
    }

My thinking is to bind the CsvTransaction properties to each DataGridTextColumn in the XAML and then set the DataContext for the DataGrid to the List<CsvTransaction at run-time, but this isn't working.

Any ideas about how I might approach this (or do it better)?

+2  A: 

Don't you have to assign the data source to the ItemsSource property of the Datagrid control?

azamsharp
+1  A: 

Use Datagrid.ItemsSource.

Benny Jobigan