Generating columns in ObjectListView C#
In normal ListView I usually generate columns on fly with something like:
var list = new List<ColumnNameSize>();
list.Add(new ColumnNameSize("Computer Name", 0));
list.Add(new ColumnNameSize("Full Computer Name", 150));
list.Add(new ColumnNameSize("Migrated", 150));
list.Add(new ColumnNameSize("Disabled", 0));
list.Add(new ColumnNameSize("Disabled & Not Migrated", 150));
generateListView(listViewObjects, list);
public static void generateListView(ListView varListView, List<ColumnNameSize> nameSizeList) {
varListView.ClearColumns();
foreach(ColumnNameSize nameSize in nameSizeList) {
varListView.AddColumn(nameSize.ColumnName, nameSize.ColumnSize);
}
}
How would I do it in ObjectList开发者_如何转开发View. I've tried multiple combinations:
public void generateListView(ObjectListView varListView, List<ColumnNameSize> nameSizeList) {
ArrayList myArrayList = new ArrayList();
foreach (ColumnNameSize nameSize in nameSizeList) {
OLVColumn columnHeader = new BrightIdeasSoftware.OLVColumn();
columnHeader.Width = nameSize.ColumnSize;
columnHeader.Text = nameSize.ColumnName;
myArrayList.Add(columnHeader);
varListView.AllColumns.Add(columnHeader);
}
Object columnsHeader = myArrayList.ToArray();
varListView.Columns.AddRange( columnsHeader);
}
But none seems to work...
Can you try this?
public void generateListView(ObjectListView varListView, List<ColumnNameSize> nameSizeList) {
List<OLVColumn> columnsList = new List<OLVColumn>();
foreach (ColumnNameSize nameSize in nameSizeList) {
OLVColumn columnHeader = new BrightIdeasSoftware.OLVColumn();
columnHeader.Width = nameSize.ColumnSize;
columnHeader.Text = nameSize.ColumnName;
columnsList .Add(columnHeader);
varListView.AllColumns.Add(columnHeader);
}
varListView.Columns.AddRange( columnsList.Cast<System.Windows.Forms.ColumnHeader>().ToArray());
}
To make the columns visible after adding them manually through code, you need to rebuild them with the following line:
varListView.RebuildColumns();
Based on Bala's answer, you get the following code:
public void generateListView(ObjectListView varListView, List<ColumnNameSize> nameSizeList)
{
List<OLVColumn> columnsList = new List<OLVColumn>();
foreach (ColumnNameSize nameSize in nameSizeList)
{
OLVColumn columnHeader = new BrightIdeasSoftware.OLVColumn();
columnHeader.Width = nameSize.ColumnSize;
columnHeader.Text = nameSize.ColumnName;
columnsList.Add(columnHeader);
varListView.AllColumns.Add(columnHeader);
}
varListView.Columns.AddRange(columnsList.Cast<System.Windows.Forms.ColumnHeader>().ToArray());
varListView.RebuildColumns();
}
For the ObjectListView to work as intended, you have to define the name of the desired property of your model object as AspectName.
Instead of first creating a list of ColumnNameSize, I'd rather add the columns one by one:
ObjectListView1.AllColumns.Add(new OLVColumn()
{
Text = "Column Header",
Width = 100,
AspectName = "myProperty"
});
ObjectListView1.RebuildColumns();
精彩评论