I'm having some problems to export a DataGridView to Excel.
So, after user choose some filters, the data is passed to another form and the user has the option to export to excel, but there's an error saying "Cannot cast object List to DataTable.
Let me show you the code...
Query to List --> Working fine
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();
}
Button Click Event
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();
}
}
On the other Form, the data loads OK in users_datagrid DataGridView. But, when User clicks on Export Button:
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();
}
Can someone help me???