Abhishek
Abhishek

Reputation: 2945

List Items are not clearing

I have a form in which I am displaying another form:

if (headerText == "")
{
    MhrtTemplateColumn objMhrtTemplateColumn = 
            new MhrtTemplateColumn("", lstUnusedChannelTags);
    objMhrtTemplateColumn.ShowDialog();
}
else
{
    MhrtTemplateColumn objMhrtTemplateColumn = 
            new MhrtTemplateColumn(ChannelDesc, lstUnusedChannelTags, CurrentTag);
    objMhrtTemplateColumn.ShowDialog();
}

These are the overloaded constructors:

public MhrtTemplateColumn(string channelDescription, List<string> channelTags)
{
    InitializeComponent();
    this.ChannelDescription = channelDescription;
    this.ChannelTags = new List<string>();
    this.ChannelTags.Clear();            
    this.ChannelTags = channelTags;
}
public MhrtTemplateColumn(string channelDescription, List<string> channelTags, string CurrentChannelTag)
{
    InitializeComponent();
    this.ChannelDescription = channelDescription;
    this.ChannelTags = new List<string>();
    this.ChannelTags.Clear();
    this.ChannelTags = channelTags;
    this.CurrentChannelTag = CurrentChannelTag;
}

This is the Window_Loaded event for MhrtTemplateColumn:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    txtChannelDescription.Text = ChannelDescription;
    if (CurrentChannelTag != null && CurrentChannelTag != "")
    {
        if(ChannelTags.Contains(CurrentChannelTag) == false)
            ChannelTags.Add(CurrentChannelTag);
        cmbChannelTag.ItemsSource = null;
        cmbChannelTag.ItemsSource = ChannelTags;
        cmbChannelTag.SelectedValue = CurrentChannelTag;
    }
    else
    {
        cmbChannelTag.ItemsSource = null;
        cmbChannelTag.ItemsSource = ChannelTags;
        cmbChannelTag.SelectedIndex = 0;
    }           
}

My problem is when the else block is executed, a new item gets added to the list. After closing the form and displaying it again with code in if block the list still has the new item added previously. Why?

Upvotes: 0

Views: 39

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103447

this.ChannelTags = new List<string>();
this.ChannelTags.Clear();            
this.ChannelTags = channelTags;

I think with this code you are trying to make a copy of channelTags? If so, this is how to do that:

this.ChannelTags = channelTags.ToList();

Your code just creates an empty list, clears it, then throws it away and assigns channelTags to the field instead.

Upvotes: 1

Related Questions