While working on the new product (and that's why the break) we got into
a DataBinding situation. We had a DTO class, something like this
public
class Employee
{
private string employeeName;
private string employeeId;
public string EmployeeName
{
get { return employeeName; }
set {
employeeName = value; }
}
public string EmployeeId
{
get { return employeeId; }
set { employeeId
= value; }
}
public Employee(string employeeName, string
employeeId)
{
this.employeeName
= employeeName;
this.employeeId
= employeeId;
}
}
and to show the data
on a DataGrid (System.Windows.Forms.DataGrid) we used an array of such
an object as a DataSource to the grid. And then we got into a
situation. How to resize the columns of the grid at runtime? Using
TableStyles ? Would the following code work (this is the method written
in the wrapper to the DataGrid and called on DataSourceChanged event)?
private
void RedrawGrid()
{
if (this.DataSource == null
|| this.Width == 0)
{
return;
}
this.TableStyles.Clear();
Array dataSource = (this.DataSource
as Array);
Type type = dataSource.GetValue(0).GetType();
//tableStyle.MappingName = type name or variable name?
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.AlternatingBackColor =
Color.GreenYellow;
foreach
(PropertyInfo property in type.GetProperties())
{
DataGridTextBoxColumn columnStyle = new DataGridTextBoxColumn();
columnStyle.MappingName = property.Name;
columnStyle.Width = this.Width/this.VisibleColumnCount;
tableStyle.GridColumnStyles.Add(columnStyle);
}
this.TableStyles.Add(tableStyle);
}
This is how you would do the stuff
if the DataSource was a DataTable. Right? No, I missed the MappingName.
Without this, the style won't be mapped to the Grid. So what do you normally set the MappingName to when you bind the grid to a DataSet/Table? answer: The TableName. Something like this
//strictly if the source is a
table, and here just for reference
tableStyle.MappingName = (this.DataSource as
DataTable).TableName;
But what would you set it to, when
it comes to an array? Does the same idea, that of the variable's name
work here? Surprisingly NO
// Works
Array dataSource = (this.DataSource
as Array);
Type type = dataSource.GetValue(0).GetType();
tableStyle.MappingName = type.Name +
"[]"; //i.e. Employee[]
dataGrid.TableStyles.Add(tableStyle);
In the case of a
DataTable, the TableStyle is mapped to the TableName (that is, the name
of a variable), while in this case, its named to the class's name
(string "Employee[]"). not the base class's name (System.Array), not
the fully qualified name ( Proteans.DataTransfer.Employee[], but just
Employee[]. And yes, no guidelines from MSDN whatsoever?
Anyway, it worked and I am happy. So
for people who were searching for a way to have the runtime column
resizing feature for a Datagrid bound to an Array, use the Array type
as the mapping name, and define the ColumnStyles etc. then on. My 2
cents.