0

我正在读取文件并使用计时器在列表视图中显示其内容。虽然我每次都使用 listview.items.clear(),但我的列表并没有清除,并且每次都会重复相同的数据来列出。

    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;
    }

请解决...

4

2 回答 2

3

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

于 2012-08-04T12:21:52.400 回答
1

此更改将解决您的问题。

   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;
    }
于 2012-08-04T12:31:33.857 回答