简体   繁体   中英

Listview.Items.Clear( ) not working

I am reading a file and displaying its content in a list view using a timer. Though i use listview.items.clear() every time, my list doesnot clear and the same data is repeated to list every time.

    private void timer1_Tick(object sender, EventArgs e)
    {
        bufferedListView1.Items.Clear();
        StreamReader sr = new StreamReader("C:\\sample.txt");
        string s;
        s = sr.ReadLine();
        while (s != null)
        {
            s = sr.ReadLine();
            var m = Regex.Match(s, @"^([a-zA-Z._]+)@([\d]+)");
            if (m.Success)
            {
                allcont ac = new allcont();
                ac.name = m.Groups[1].Value;
                ac.number = m.Groups[2].Value;
                con.Add(ac);
                s = sr.ReadLine();
            }
        }
        foreach (allcont aa in con)
        {
            ListViewItem i = new ListViewItem(new string[] { aa.name, aa.number });
            i.Tag = aa;
            bufferedListView1.Items.Add(i);
        }
        sr.Close();

    }

    contacts con = new contacts();
    public class contacts:List<allcont>
    { 

    }
    public class allcont
    {
        public string name;
        public string number;
    }

Solution please...

似乎您没有在清洁con容器,因此它的内容会在每个计时器滴答后附加(而不是被替换)。

This change will fix your problem.

   private void timer1_Tick(object sender, EventArgs e)
    {
        bufferedListView1.Items.Clear();
        StreamReader sr = new StreamReader("C:\\sample.txt");
        contacts con = new contacts();
        string s;
        s = sr.ReadLine();
        while (s != null)
        {
            s = sr.ReadLine();
            var m = Regex.Match(s, @"^([a-zA-Z._]+)@([\d]+)");
            if (m.Success)
            {
                allcont ac = new allcont();
                ac.name = m.Groups[1].Value;
                ac.number = m.Groups[2].Value;
                con.Add(ac);
                s = sr.ReadLine();
            }
        }
        foreach (allcont aa in con)
        {
            ListViewItem i = new ListViewItem(new string[] { aa.name, aa.number });
            i.Tag = aa;
            bufferedListView1.Items.Add(i);
        }
        sr.Close();

    }

    public class contacts:List<allcont>
    { 

    }
    public class allcont
    {
        public string name;
        public string number;
    }

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