简体   繁体   中英

c# binding IDictionary with Listbox

I am new to windows form and learning. I have a simple code with a form populated with listbox1. I am trying to populate it by binding it to IDictionary instance.

static IDictionary<string, string> Bind_Data = new Dictionary<string, string>();

    Binding myBinding = new Binding("DataSource", Bind_Data, "Key");   

    listBox1.DataBindings.Add(myBinding);

I am getting the following error when I run this code.

error: System.Reflection.TargetInvocationException: Property accessor 'Key' on object 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' threw the following exception:'Object does not match target type.' ---> System.Reflection.TargetException: Object does not match target type. at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)

Really appreciate if someone can help me understand this error.

I can use

listBox1.DataSource=new Binding(Bind_Data, null);
listBox1.ValueMemeber="Key";
listBox1.DisplayMember="Value";

But I want to use Binding

Looking at the MSDN docs for that constructor: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.binding.-ctor?view=netframework-4.7.2#System_Windows_Forms_Binding__ctor_System_String_System_Object_System_String_

The data source argument can only be certain objects - the Dictionary type doesn't implement IList, which I suspect is the reason you are getting the above exception.

If your underlying type must be a Dictionary, you may want to wrap it in a custom class which implements IList so that you get your desired binding, otherwise just use the second style you have above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM