Search code examples
c#winformsobjectlistview

Initialize an ObjectListView with Buttons


I have an ObjectListView with three columns. The first displays the name of a file, and the other two must have buttons that allow to perform download and delete actions.

However, to initialize the ObjectListView, I first call a method that returns a list of strings with the file names.

How do I get the names of these files to load in the first column of ObjectListView, accompanied by the buttons in the other two columns?

Thanks.


Solution

  • How do I get the names of these files to load in the first column of ObjectListVie

    You can use AddObjects to add a list of objects to the ObjectListView. You can use OlvColumn.AspectName to determine what gets shown e.g. "ToString". You might want to create a class instead of just shoving strings in though.

            olvColumn1.AspectName = "ToString";
    
            olv.AddObjects(new []
            {
                @"c:\temp\1.txt",
                @"c:\temp\2.txt",
                @"c:\temp\3.txt"
            });
    

    accompanied by the buttons in the other two columns?

    You can create buttons in a column as so:

            olvColumn2.IsButton = true;
            olvColumn2.ButtonSizing = BrightIdeasSoftware.OLVColumn.ButtonSizingMode.CellBounds;
            olvColumn2.AspectGetter =(s)=>"Kill";
            olv.ButtonClick += (s, e) => 
            {
                if(e.Column == olvColumn2) 
                    try
                    {
                        if(File.Exists((string)e.Model))
                            File.Delete((string)e.Model);
                        else
                            MessageBox.Show("File not found");
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
            };