如何将指定JSON数据绑定到DevExpress WinForms LookUpEdit控件?
Got it, let's get this JSON binding to your LookUpEdit working properly. Here's what you need to do:
First, Fix Your JSON File
Your current JSON has unquoted keys (like 01 instead of "01"), which isn't valid JSON. Update your numbers.json to use quoted keys:
{ "01": "One", "02": "Two", "03": "Three", "04": "Four", "05": "Five", "06": "Six", "07": "Seven", "08": "Eight", "09": "Nine", "10": "Ten" }
Adjust Your Binding Code
When you parse the JSON into a JObject, it's a collection of JProperty entries, but LookUpEdit needs a simple list of objects with clear Key and Value properties to bind to. Here's the corrected code:
using Newtonsoft.Json.Linq; using System.Linq; // Read and parse the valid JSON var json = File.ReadAllText(@"numbers.json"); var jsonObject = JObject.Parse(json); // Convert JObject properties into a bindable list var numberItems = jsonObject.Properties() .Select(prop => new { Key = prop.Name, Value = prop.Value.ToString() }) .ToList(); // Configure the LookUpEdit control lookUpEdit1.Properties.DropDownRows = numberItems.Count > 10 ? 10 : numberItems.Count; lookUpEdit1.Properties.DisplayMember = "Key"; lookUpEdit1.Properties.ValueMember = "Value"; lookUpEdit1.Properties.DataSource = numberItems; // Optional: Force the control to refresh and show the new data lookUpEdit1.Refresh();
Why This Works
jsonObject.Properties()gives us each key-value pair from the JSON as aJPropertyobject.- We use LINQ to project each
JPropertyinto an anonymous type with explicitKeyandValueproperties—this is the structure LookUpEdit expects for binding. - Setting this list as the
DataSourcelets the control mapDisplayMember(what the user sees) andValueMember(the underlying value) correctly.
Optional: Use a Strongly-Typed Class
If you want to avoid anonymous types (good for reusability or type safety), create a simple class:
public class NumberEntry { public string Key { get; set; } public string Value { get; set; } }
Then adjust the LINQ query to use this class:
var numberItems = jsonObject.Properties() .Select(prop => new NumberEntry { Key = prop.Name, Value = prop.Value.ToString() }) .ToList();
That's it—your LookUpEdit should now populate correctly with the JSON data!
内容的提问来源于stack exchange,提问作者user1372430
相关产品推荐
相关产品推荐

