I am trying to work around the problem described in this question. Basically I need the contents of a DataGridView to update when the underlying data are changed.
I am trying the 'data binding with an intermediate data source' approach (number three of the original options I outlined). To do this I have created a DataTable within the UI scope, which contains the same number of cells as the DataGridView. I then populate it with the relevant data and bind it to the DGV. This DataTable contains a subset of the underlying data, laid out as per the requirements of the user interface.
However, the DataTable does not update when the underlying data changes. I had tried to ensure that the table was populated with references rather than values, by specifying that the data type was 'object'. However, it seems that this doesn't work as I had hoped it might. Testing shows that the contents of the DataTable remain unchanged once entered. Presumably they are values.
To give a simplified example, say I have got a two-by-two DataGridView and want to populate it with the some basic statistics for a dog and a house, which form part of a much larger object model. What I am doing is something like this:
class Dog{
string Name;
int Age;
float WeightInKG;
}
class House{
string NameOrNumber;
int YearBuilt;
bool IsPainted;
}
Initialise the objects and create the data source, bound to the DGV:
DataTable dgvContents;
House thisHouse = new House();
Dog thisDog = new Dog();
InitObjects();
CreateDataTable();
private void InitObjects() {
thisHouse.YearBuilt = 1970;
thisHouse.IsPainted = true;
thisDog.Name = "Spot";
thisDog.Age = 3;
}
private void CreateDataTable() {
dgvContents = populateDataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = dgvContents;
dataGridView1.DataSource = SBind;
}
private DataTable PopulateDataTable() {
DataTable thisTable = new DataTable("UITable");
int cols = 2;
int rows = 2;
for (int i = 0; i < cols; i++)
{
thisTable.Columns.Add("", typeof(object));
}
for (int j = 0; j < rows; j++)
{
thisTable.Rows.Add(new object[cols]);
}
thisTable.Rows[0][0] = thisdog.Name;
thisTable.Rows[0][1] = thisdog.Age;
thisTable.Rows[1][0] = thisHouse.IsPainted;
thisTable.Rows[1][1] = thisHouse.YearBuilt;
return thisTable;
}
This method is only viable if the DataTable I am creating (dgvContents
) contains references rather than values. Is this possible?