Masoud Masoud - 1 month ago 7
C# Question

Change the customized ListView.Items after each build

I create a customized

ListView
that inherited from standard
ListView
in
.NET
to show an
enum
values as its
Items
(
WinForms
project):

public class ScrapGroupsListView : ListView
{
public event EventHandler SelectedColorChanged;

private ScrapGroup _selectedGroup = ScrapGroup.None;

[DefaultValue(ScrapGroup.None)]
public ScrapGroup SelectedScrapGroup
{
get { return _selectedGroup; }
set
{
if (_selectedGroup != value)
{
_selectedGroup = value;
foreach (ListViewItem item in this.Items)
{
if (item != null)
{
if (item.Tag != null)
{
var itemColor = (ScrapGroup)item.Tag;
if (itemColor == ScrapGroup.None)
item.Checked = value == ScrapGroup.None;
else
item.Checked = value.HasFlag(itemColor);
}
}
}

if (SelectedColorChanged != null)
SelectedColorChanged.Invoke(this, EventArgs.Empty);
}
}
}

public ScrapGroupsListView()
{
this.Items.Clear();
this.CheckBoxes = true;
this.HeaderStyle = ColumnHeaderStyle.None;
this.View = View.List;

foreach (var value in Enum.GetValues(typeof(ScrapGroup)).Cast<ScrapGroup>())
{
this.Items.Add(new ListViewItem()
{
Name = value.ToString(),
Text = value.ToString(),
Tag = value,
});
}
}

protected override void OnItemChecked(ItemCheckedEventArgs e)
{
base.OnItemChecked(e);

var checkedScrapGroup = (ScrapGroup)e.Item.Tag;

if (e.Item.Checked)
if (checkedScrapGroup == ScrapGroup.None)
SelectedScrapGroup = ScrapGroup.None;
else
SelectedScrapGroup |= checkedScrapGroup;
else
SelectedScrapGroup &= ~checkedScrapGroup;
}
}


ScrapGrouop
is my enum:

[Flags]
public enum ScrapGroup
{
None=0,
M=1,
E=2,
N=4,
H=8
}


when I put the
ScrapGroupsListView
to my form, everything is OK and the control has no Items:

enter image description here

But each time I build my project, the
ScrapGroup
values add to
ScrapGroupsListView.Items
(design-time):

after 1st build:

enter image description here

after 2nd build:

enter image description here

and so on.

Where is the problem?

Answer

Instead of constructor try:

protected override void OnCreateControl()
    {
        base.OnCreateControl();

        this.Items.Clear();
        this.CheckBoxes = true;
        this.HeaderStyle = ColumnHeaderStyle.None;
        this.View = View.List;

        foreach (var value in Enum.GetValues(typeof(ScrapGroup)).Cast<ScrapGroup>())
        {
            this.Items.Add(new ListViewItem()
            {
                Name = value.ToString(),
                Text = value.ToString(),
                Tag = value,
            });
        }
    }
Comments