I've been at this for a few days, and I can't seem to find the correct approach to bind dynamic data to a DataGridView.
I'm downloading data from a web API that is delivered in JSON. Newtonsoft JSON deserializes the data and stores it in a dynamic. I can bind this to my DataGridView with no problems. I can even add members to it.
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
}
I'm trying to define my own dynamic object to store summaries of the data retrieved but I can't figure out how to create a dynamic data model that I can bind to the DataGridView. I've tried a number of options, I assumed I needed to create a List populated with ExpandoOject, but I can't get that to bind and show the data. I have also tried a List of Dictionaries, but that hasn't really worked either.