/// <summary>
/// Fixes column names. Requires all ColumnHeaders to have members (set GenerateMember to <c>true</c>).
/// </summary>
/// <param name="list">The ListView.</param>
public static void FixColumnNames(ListView list)
{
List<ColumnHeader> columns =
new List<ColumnHeader>
();
foreach (ColumnHeader column in list.Columns)
{
if (string.IsNullOrEmpty(column.Name))
{
columns.Add(column);
}
}
if (columns.Count == 0)
{
// no need to fix names
return;
}
Control parent = list.Parent;
while (parent != null)
{
FieldInfo listInfo = parent.GetType().GetField(list.Name, BindingFlags.NonPublic | BindingFlags.Instance);
if (listInfo != null)
{
// found a member with given name, let's check if it points to the same object
if (object.ReferenceEquals(listInfo.GetValue(parent), list))
{
// yes, this member points to our object
break;
}
}
parent = parent.Parent;
}
if (parent != null)
{
foreach (ColumnHeader column in columns)
{
FieldInfo columnInfo = null;
// for all fields
foreach (FieldInfo field in parent.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
// ...find the one pointing to column we're looking for
if ((field.FieldType == column.GetType()) && (object.ReferenceEquals(field.GetValue(parent), column)))
{
// same type, same value -> yes, this is the member we're looking for
columnInfo = field;
break;
}
}
if (columnInfo != null)
{
try
{
column.Name = columnInfo.Name;
}
catch
{
// No idea why, but we don't want any exceptions...
}
}
else
{
// no member found
}
}
}
else
{
// no parent found
}
}