For the case where the ItemsSource of the DataGrid is a collection, you could refer to the following code.
MainWindow.xaml:
<DockPanel>
<Button Content="Export data" Click="Export_Click" DockPanel.Dock="Bottom"/>
<DataGrid x:Name="dataGrid" ItemsSource="{Binding Products}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Id" Binding="{Binding Id}" />
<DataGridCheckBoxColumn Header="Checked" Binding="{Binding IsAvailable}"/>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
namespace DataGridToCVS
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
this.Products = new List<Product>();
for (int i = 0; i < 100; ++i)
{
Product item = new Product();
item.Id = i;
item.Name = string.Format("Item {0}", i);
bool b = (i % 2).Equals(0);
item.IsAvailable = b;
this.Products.Add(item);
}
}
public IList<Product> Products
{
get;
private set;
}
private void Export_Click(object sender, RoutedEventArgs e)
{
var filepath = @"C:\Users\...\Desktop\test.csv";
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(new FileStream(filepath, FileMode.Create, FileAccess.Write));
DataSet ds = Products.ConvertToDataSet("table");
DataTable dt = ds.Tables[0];
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
}
public static class C
{
public static DataSet ConvertToDataSet<T>(this IEnumerable<T> source, string name)
{
if (source == null)
throw new ArgumentNullException("source ");
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
var converted = new DataSet(name);
converted.Tables.Add(NewTable(name, source));
return converted;
}
private static DataTable NewTable<T>(string name, IEnumerable<T> list)
{
PropertyInfo[] propInfo = typeof(T).GetProperties();
DataTable table = Table<T>(name, list, propInfo);
IEnumerator<T> enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
table.Rows.Add(CreateRow<T>(table.NewRow(), enumerator.Current, propInfo));
return table;
}
private static DataRow CreateRow<T>(DataRow row, T listItem, PropertyInfo[] pi)
{
foreach (PropertyInfo p in pi)
row[p.Name.ToString()] = p.GetValue(listItem, null);
return row;
}
private static DataTable Table<T>(string name, IEnumerable<T> list, PropertyInfo[] pi)
{
DataTable table = new DataTable(name);
foreach (PropertyInfo p in pi)
table.Columns.Add(p.Name, p.PropertyType);
return table;
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsAvailable { get; set; }
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.
[5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html