如何将datagridview与字典项绑定 [英] How to bind a datagridview with dictionary items

查看:340
本文介绍了如何将datagridview与字典项绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用C#将字典项绑定到Windows窗体中的datagridview。





例如



考虑







How to bind dictionary items into datagridview in windows forms using C#.


For example

Consider



Dictionary<string, double,double,double> d =new Dictionary<string,int>()
	{
	    {"Apple",255,0,0},
	    {"Orange",255,165,0},
	    {"Grapes", 238,130,238}
	    
	};





我想在datagridview中添加它们。



如何做到这一点



I want to add them in a datagridview.

How to do this

推荐答案

首先,该代码不会编译,因为Dictionary只接受一个Key类型和一个Value类型,而不是Key Type和3 Value类型。 />


接下来,您无法将DGV绑定到Dictionary。字典是2个集合,一个是键,另一个是值。它不是Key-Value的单一集合。



您必须将字典中的项目转换为其他数据结构,如DataTable或List< t, >或者实现以下接口之一的任何其他类型:IList,IListSource,IBindingList或IBindingListView。字典< k,v> class不会那样做。
First, that code won't compile because Dictionary will only take a single Key type and a single Value type, not a Key Type and 3 Value types.

Next, you can't bind a DGV to a Dictionary. A dictionary is 2 collections, one of keys and another of values. It's not a single collection of Key-Value.

You would have to convert the items in the dictionary to some other data structure, like a DataTable or List<t,> or any other type that implements one of the following interfaces: IList, IListSource, IBindingList or IBindingListView. The Dictionary<k,v> class does not do that.


你可以使用Array或List作为你的Grdiview的DataSource。因此,将所有元素作为列表并将其绑定到网格。

Well you can use Array or List as a DataSource to your Grdiview. So get all the elements as a list and bind it to the grid.
dataGridView.DataSource =  (from d in dictionary orderby d.Value select new { d.Key, d.Value}).ToList();





-KR



-KR


这篇关于如何将datagridview与字典项绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆