问题
I've got a list of name-value pairs that I'm wanting to put in a nice report format. Is it possible to use this as a data source for a ReportViewer object? This is in WinForms and ASP.
回答1:
I was able to convert the Dictionary to a DataTable and use that as the DataSource.
var table = new DataTable();
var kvps = dictionary.ToArray();
table.Columns.AddRange(kvps.Select(kvp => new DataColumn(kvp.Name)).ToArray());
table.LoadDataRow(kvps.Select(kvp => kvp.Value).ToArray(), true);
bindingSource.DataSource = table;
Voilà
回答2:
I believe you'll have to create a class to encapsulate the items you'd like to display in the report. See my answer to this question for how to bind a class to a report.
The code's in VB.NET but you'll be able to follow it quite easily.
回答3:
I don't think that's not going to naturally bind in the ReportViewer. Just put them in a list of custom objects with the properties you want to bind to. It wouldn't be a lot of overhead (like a List.
回答4:
Dictionaries are not suited as data source for lists. They are optimized for retrieving values for given keys. Nevertheless, you can retrieve the keys, the values and key/value pairs from the dictionary as follows:
var keys = dict.Keys;
var values = dict.Values;
var keyValuePairs = dict.OrderBy(x => x.Value);
foreach (KeyValuePair<string, int> item in keyValuePairs) {
Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
}
来源:https://stackoverflow.com/questions/8535877/how-to-bind-report-viewer-with-a-dictionarystring-int-as-the-data-source