Question

I have the following class:

public class people
{
    public string name { get; set; }
    public string hobby { get; set; }
}

And I want to display a list like this:

no | name | hobby
-----------------------
01 | kim  | tv
02 | kate | pc
03 | kim  | tv
04 | kate | pc

The only way i know to achieve this is to change people class to

public class people
{
    public string no{ get; set; }
    public string name { get; set; }
    public string hobby { get; set; }
}

and loop List<people> to set every no property.

Is there a better way to add an index number column?

Was it helpful?

Solution

Yes, you can achieve what you want by handling the ´FormatRow´ event like this:

objectListView1.FormatRow += delegate(object sender, FormatRowEventArgs args) {
    args.Item.Text = args.RowIndex.ToString();
};

This will show the zero-based index on the first column of the ObjectListView. If you want it to show as 01, 02... you can specify a format string and an offset like:

args.Item.Text = (args.RowIndex + 1).ToString("D2");

As a side note: Its not possible to achive this using the AspectGetter (which would be more elegant), because at the time its called, the row was not yet added to the OLV and thus has no index information.

// !!! won't work !!!
indexColumn.AspectGetter += delegate(object rowObject) {
    return objectListView1.IndexOf(rowObject).ToString();
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top