I am successfully binding to a list of objects and setting this as the DataGridViews datasource. Definiting columns, at run time, which include the appropriate DataPropertyNames.
However I now need to add a list to my object class. The size of this list is dynamic, but always the same size for all instances of my object.
So my question is how can I create my DataGridViewTextBoxColumn to create a column for each items within this list?
Below is my object code, which has been simplified for this question. Within the languages Dictionary will be something like:
- "English", "Hello"
- "German", "Hallo"
- "Spanish", "Hola"
Ideally the Key would appear as the column name.
Looking like this (each row is a StringItem):
public class StringItem
{
#region Attributes ########################################################################
string name; // String name, used to generate the enum for referencing
string comment; // Helpful description of the string item.
Dictionary<string, string> languages = new Dictionary<string, string>(); // For language strings.
#endregion
#region Public Functions ##################################################################
public string Name
{
get { return name; }
}
public string Comment
{
get { return comment; }
set { comment = value; }
}
public Dictionary<string, string> Languages
{
get { return languages; }
set { languages = value; }
}
#endregion
}
Update: I believe the suggested link in the comments isn't trying to achieve quite the same thing, however it is useful.
I can see that by adding the follow code to my StringItem I can directly access the language dictionary doing myObj["English"]
public string this[string key]
{
get
{
return languages[key];
}
set
{
languages[key] = value;
}
}
However the DataPropertyName, for each column, doesn't quite work liek this. I assume it uses reflections? Can anyone confirm this and tell me if I can implement my own reflection, or whatever DataPropertyName is using, to get my dictionary item.
This is how I set up the columns:
DataGridViewColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Name";
column.Name = "Name";
dgvStrings.Columns.Add(column);
foreach (string lang in ProjectSettings.Languages)
{
column = new DataGridViewTextBoxColumn();
column.DataPropertyName = lang; // <<<< THIS ISN'T WORKING.
column.Name = lang;
dgvStrings.Columns.Add(column);
}