views:

62

answers:

4

In a C# Winform application (3.5) there are numerous forms each with different listview controls. While each listview control uses different datasets the basic formatting of each remains the same.

Basic formatting takes this form:

  /* appearance */
  this.lstA.View = View.Details;
  this.lstA.AllowColumnReorder = true;
  this.lstA.CheckBoxes = false;
  this.lstA.FullRowSelect = true;
  this.lstA.GridLines = false;
  this.lstA.Sorting = SortOrder.Ascending;

What I would like to do is create a class that can be used to set the initial format of the listview.

How do I pass the listview (by reference?) to the class so that the appearance properties can be set?

+2  A: 

Perhaps you can subclass the ListView then set your default functionality and then just use your subclassed ListView everywhere you are using a normal ListView now.

Frank Hale
+2  A: 

You could pass the control by reference to do that, but it might be easier in the long run to just subclass ListView and set the defaults you need.

Michael Todd
How would you drop a subclassed ListView on a Form?
Asher
@Asher After creating it, I would add it to the Toolbar via "Choose Toolbox Items" under the Tools menu in Visual Studio. The subclassed control would then be available for me to drag and drop (or double-click) from the Toolbox when my form is visible.
Michael Todd
@Michael, thanks
Asher
@Michael. Just tried this and the subclassed listView was available on the toolbar without adding it! How cool is that
Asher
Good to hear it showed up automatically. I was probably doing it "the old way."
Michael Todd
+2  A: 

I think you have several options, not sure which one is best for you, but you can consider:

  1. creating a class that inherits from ListView, and in the constructor set whatever you need. use this class in your forms. this is good if you need the same appearance no matter what.
  2. create a class with static method SetListViewAppearance(ListView controlToSet). in this method you can set whatever you need. this will require you in each form to call this method before, probably in the form load event.

I would go for the first solution, unless you have some restriction.

Ami
+1  A: 

To add to the other answers:

public static class MyExtensionMethods
    {
        public static void InitializeAppearance(this ListView aListView)
        {
            aListView.View = View.Details;
            aListView.AllowColumnReorder = true;
            aListView.CheckBoxes = false;
            aListView.FullRowSelect = true;
            aListView.GridLines = false;
            aListView.Sorting = SortOrder.Ascending;
        }
    }
}

and you call it listview1.InitializeAppearance();

Asher
Thanks works well.
John M