我已经在这几天了,我似乎无法找到将动态数据绑定到DataGridView的正确方法。
我正在从以JSON格式提供的Web API下载数据。 Newtonsoft JSON反序列化数据并将其存储在动态数据中。我可以将它绑定到我的DataGridView没有问题。我甚至可以添加成员。
public partial class frmTBAstatistics : Form
{
private static frmTBAstatistics _instance;
public static frmTBAstatistics GetInstance()
{
if (_instance == null)
_instance = new frmTBAstatistics();
return _instance;
}
//private dynamic matches;
private dynamic matches;
private dynamic teamstats = new BindingList<object>();
//Dictionary<string, int> stats = new Dictionary<string, int>();
public frmTBAstatistics()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
LoadMatchData();
dynamic bluescores = new AdvancedList<object>();
dynamic redscores = new BindingList<object>();
foreach (dynamic match in matches)
{
int index = 0;
foreach (object teamkey in match.alliances.blue.teams)
{
var team = new ExpandoObject() as IDictionary<string, object>;
team.Add("key", match.alliances.blue.teams[index++]);
team.Add("match", match.key);
dynamic scorerecord = match.score_breakdown.blue;
foreach(Newtonsoft.Json.Linq.JProperty pi in scorerecord)
{
team.Add(pi.Name, pi.Value);
}
teamstats.Add(team);
bluescores.Add(scorerecord);
redscores.Add(match.score_breakdown.red);
}
}
dgvTBAstats.DataSource = teamstats;
dgvTBAstats.Refresh();
}
private void LoadMatchData()
{
string matchpath = Files.appPath + Files.matchdata;
if (File.Exists(matchpath))
{
System.IO.StreamReader matchfile = new System.IO.StreamReader(matchpath);
string response = matchfile.ReadToEnd();
matchfile.Close();
matches = JsonConvert.DeserializeObject(response);
}
}
// End Class
}
我正在尝试定义自己的动态对象来存储检索到的数据的摘要,但我无法弄清楚如何创建可以绑定到DataGridView的动态数据模型。我已经尝试了很多选项,我假设我需要创建一个填充了ExpandoOject的List,但我无法将其绑定并显示数据。我也尝试了一个字典列表,但这也没有真正起作用。