简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM