C#无法将列表转换为DataTable

时间:2018-06-27 13:20:40

标签: c#

在将DataGridView导出到Excel时遇到一些问题。

因此,在用户选择了一些过滤器之后,数据将传递到另一种表单,并且用户可以选择导出到excel,但是会出现错误消息“无法将对象列表转换为DataTable。

让我告诉你代码...

查询列表->运行正常

public class Users
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

public IEnumerable<Users> LoadUsers()
    {
        var ctx = new Entities();
        var query = (from p in ctx.tblUser.AsQueryable()
                     join c in ctx.tblNames on p.NameID equals c.NameID
                     join e in ctx.tblAddresses on p.AddressID equals e.AddressID
                     select new Users
                     {
                         ID = p.ProjetoID,
                         Name = c.Name,
                         Address = e.Address
                     });
        return query.ToList();
    }

按钮点击事件

private void BtnSearch_Click(object sender, EventArgs e)
    {
        if(LoadUsers() == null)
        {
            MessageBox.Show("No results!", "No results", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            UsersSearch_List searchlist = new UsersSearch_List();
            searchlist.users_datagrid.DataSource = LoadUsers();
            searchlist.MdiParent = MdiParent;
            searchlist.Show();
        }
    }

在另一个Form上,数据将OK加载到users_datagrid DataGridView中。但是,当用户单击“导出”按钮时:

private void exportToolStripMenuItem_Click(object sender, EventArgs ev)
    {
        DataTable dt = new DataTable();
        dt = (DataTable)users_datagrid.DataSource; //--> The error occurs here... Cannot cast object List to DataTable.

        //This is a Helper I have to convert List to DataTable, but it don't works eather!!!
        //DataTable dt = ConvertListToDataTable.ToDataTable(projetos_datagrid);

        if (saveFileDialog.ShowDialog() != DialogResult.OK)
        {
            return;
        }
        string TargetFileName = saveFileDialog.FileName;
        try
        {
            CreateExcelFile.CreateExcelDocument(dt, TargetFileName);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
            return;
        }
        Process process = new Process();
        process.StartInfo = new ProcessStartInfo(TargetFileName);
        process.Start();
    }

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您应该创建一个新的DataTable并使用列表填充它:

    public static DataTable ToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }