我有一些代码可以将数据从DataGrid转换为CSV文件。这很好但我需要转换所有行,而不仅仅是当前屏幕上显示的行(Itemsource)是否有办法获取所有行?
// create one file gridview.csv in writing mode using streamwriter
StreamWriter sw = new StreamWriter("c:\\gridview.csv");
// now add the gridview header in csv file suffix with "," delimeter except last one
for (int i = 0; i < dgProductList.Columns.Count; i++)
{
sw.Write(dgProductList.Columns[i].Header);
if (i != dgProductList.Columns.Count)
{
sw.Write(",");
}
}
// add new line
sw.Write(sw.NewLine);
// iterate through all the rows within the gridview
foreach (DataGridRow dr in Utilities.GetDataGridRows(dgProductList))
{
// iterate through all colums of specific row
for (int i = 0; i < dgProductList.Columns.Count; i++)
{
// write particular cell to csv file
DataGridCell cell = Utilities.GetCell(dgProductList,dr, i);
TextBlock tb = cell.Content as TextBlock;
sw.Write(tb.Text);
if (i != dgProductList.Columns.Count)
{
sw.Write(",");
}
}
// write new line
sw.Write(sw.NewLine);
}
// flush from the buffers.
sw.Flush();
// closes the file
sw.Close();
public static IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row) yield return row;
}
}
谢谢
答案 0 :(得分:0)
很可能是虚拟化问题。尝试在数据网格属性上设置VirtualizingStackPanel.IsVirtualizing="False"
。