No i used 2.1 version in that it was not giving Problem for Item Source and it was returning all values and exporting the Data as desired but i shifted to 2.2 version and it started giving problem.
Here is the code.(source = (grid.ItemsSource as System.Collections.IList);)
[HTML]
public string ExportDataGrid(bool withHeaders, DataGrid grid)
{
string colPath;
System.Reflection.PropertyInfo propInfo;
System.Windows.Data.Binding binding;
System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
IList source;
if (grid.SelectedItems.Count > 0)
{
source = (grid.SelectedItems as System.Collections.IList);
}
else
{
source = (grid.ItemsSource as System.Collections.IList); //Giving error
}
if (source == null)
return "";
List<string> headers = new List<string>();
foreach (DataGridBoundColumn col in grid.Columns)
{
if (col is DataGridBoundColumn)
{
headers.Add(FormatCSVField(col.Header.ToString()));
}
};
strBuilder
.Append(String.Join(",", headers.ToArray()))
.Append("\r\n");
foreach (Object data in source)
{
List<string> csvRow = new List<string>();
foreach (DataGridColumn col in grid.Columns)
{
if (col is DataGridBoundColumn)
{
binding = (col as DataGridBoundColumn).Binding;
colPath = binding.Path.Path;
propInfo = data.GetType().GetProperty(colPath);
if (propInfo != null)
{
csvRow.Add(FormatCSVField(propInfo.GetValue(data, null).ToString()));
}
}
}
strBuilder
.Append(String.Join(",", csvRow.ToArray()))
.Append("\r\n");
}
return strBuilder.ToString();
}
private void BuildStringOfRow(StringBuilder strBuilder, List<string> values, string strFormat)
{
switch (strFormat)
{
case "XML":
strBuilder.AppendLine("<Row>");
strBuilder.AppendLine(String.Join("\r\n", values.ToArray()));
strBuilder.AppendLine("</Row>");
break;
case "CSV":
strBuilder.AppendLine(String.Join(",", values.ToArray()));
break;
}
}
private static string FormatField(string data, string format)
{
switch (format)
{
case "XML":
return String.Format("<Cell><Data ss:Type=\"String\">{0}</Data></Cell>", data);
case "CSV":
return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));
}
return data;
}
[/HTML]