List <t>到datatable返回空 - WPF

时间:2016-11-17 22:40:34

标签: c# wpf datatable datagrid

我使用下面的代码从datatable填充List<double[]> list 但是数据表没有填充。

private void LoadThis(object sender, EventArgs e)
        {
            X model = DataContext as X;

            List<double[]> list = new List<double[]>();
            for (int i = 0; i < model.RowFijtable; i++)
            {
                double[] rowdata = new double[model.ColFijtable];
                for (int j = 0; j < model.ColFijtable; j++)
                {
                    rowdata[j] = model.TauTable[i, j];
                }
                list.Add(rowdata);
            }
            DataTable table = ConvertListToDataTable(list);
            dataGridView1.ItemsSource = table.AsDataView(); //Is this correct?
}

  private DataTable ConvertListToDataTable(List<double[]> list)
    {
        DataTable table = new DataTable();

        // Get max columns.
        int columns = 0;
        foreach (var array in list)
        {
            if (array.Length > columns)
            {
                columns = array.Length;
            }
        }

        // Add columns.
        for (int i = 0; i < columns; i++)
        {
            table.Columns.Add();
        }

        // Add rows.
        foreach (var array in list)
        {
            table.Rows.Add(array);
        }

        return table;
    }

这就是我将信息放在XAML

中的方式
<Grid>
    <DataGrid HorizontalAlignment="Stretch"
     VerticalAlignment="Stretch"
     Name="dataGridView1"
     Loaded="LoadThis"
     ItemsSource="{Binding}"
     AutoGenerateColumns="True"/>
</Grid>

我可以看到列和行的数量正确传递给数据表但没有数据值,即使List有完整的数据集!

我也尝试过dataGridView1.DataSource = table;,但这让我误以为“Datagrid不包含DataSource的定义”..

1 个答案:

答案 0 :(得分:1)

调用table.Rows.Add(array)似乎将整个数组放入第一列值。要将数组元素放入连续的列中,请尝试以下操作:

    private DataTable ConvertListToDataTable(List<double[]> list)
    {
        DataTable table = new DataTable();

        // Get max columns.
        int columns = 0;
        foreach (var array in list)
        {
            if (array.Length > columns)
            {
                columns = array.Length;
            }
        }

        // Add columns.
        for (int i = 0; i < columns; i++)
        {
            // Provide default column name & data type
            table.Columns.Add("Column" + (i+1).ToString(), typeof(double) );
        }

        // Add rows.
        foreach (var array in list)
        {
            // assign each array element to the appropriate column
            var row = table.NewRow();
            for (int i = 0; i < array.Length; ++i )
                row.SetField( i, array[i] );
            table.Rows.Add(row);
        }

        return table;
    }