How to bind Report Viewer with a Dictionary<string,int> as the data source?

空扰寡人 提交于 2019-12-12 03:05:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!