通过计时器C#删除ListView中的项目

时间:2013-06-13 10:58:28

标签: c# listview timer

我有一个带有一些entrys的C#ListView,一个用于删除第一个条目的Methode和一个用于调用此方法的Timer。我的问题是,计时器运行良好(我通过调用MessageBox检查了这一点)并且删除方法也很好(我通过使用Button而不是通过计时器调用此方法来检查)。但是计时器仍然无法从我的ListView中删除项目。

我的代码:

    void Button1Click(object sender, EventArgs e)
    {
        removeItems();
    }

    private void timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
    {
        removeItems();      
    }

    void removeItems()
    {
        MessageBox.Show("Hello from the removeMethod");
        listViewTeam.Items.RemoveAt(0);
    }

对removeItems()的两次调用;让messageBox出现,但只有Button也允许删除listView的第一个项目。

有人可以帮我知道如何通过计时器删除第一个项目吗?

7 个答案:

答案 0 :(得分:2)

您使用的计时器不是线程安全的。您应该使用System.Timer而不是System.Windows.Forms.Timer,因为它会自动在UI线程上运行。那么你的代码将完美运行。

答案 1 :(得分:1)

您似乎正在使用System.Timer,这意味着您的Elapsed回调可能不一定会在UI线程上调用。您可以使用Invoke

来确保它
if (listViewTeam.InvokeRequired)
{
    listViewTeam.Invoke((MethodDelegate)delegate { listViewTeam.Items.RemoveAt(0); });
}

甚至可以更轻松地将计时器的SynchronizingObject属性设置为包含ListView的表单,您的代码就可以正常运行。

答案 2 :(得分:0)

您需要使用delegate从后台线程安全地与UI控件交互(这是您在实现Timer >正在执行的操作):

void Button1Click(object sender, EventArgs e)
{
    removeItems();
}

private void timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
    removeItems();      
}

void removeItems()
{
    MessageBox.Show("Hello from the removeMethod");
    RemoveListViewItem(0);
}

public delegate void InvokeRemoveListViewItem(Int32 ItemIndex);
public void RemoveListViewItem(Int32 ItemIndex)
{
    if (InvokeRequired)
    {
        try { Invoke(new InvokeRemoveListViewItem(RemoveListViewItem), new Object[] { ItemIndex }); }
        catch (Exception)
        {
            //react to the exception you've caught
        }
    }

    listView.RemoveAt(ItemIndex);
}

答案 3 :(得分:0)

就像SLC说你需要使用BeginInvoke。就个人而言,我已经解决了这个问题

  public AddListItem myDelegate;

答案 4 :(得分:0)

答案 5 :(得分:0)

                               Windows.Forms       System.Timers         System.Threading 
Timer event runs on what thread?    UI thread      UI or worker thread   Worker thread 
Instances are thread safe?          No             Yes                   No 
Familiar/intuitive object model?    Yes            Yes                   No 
Requires Windows Forms?             Yes            No                    No 
Metronome-quality beat?             No             Yes*                  Yes* 
Timer event supports state object?  No             No                    Yes 
Initial timer event schedulable?    No             No                    Yes 
Class supports inheritance?         Yes            Yes                   No

* Depending on the availability of system resources (for example, worker threads) 

答案 6 :(得分:-1)

首先启动计时器。但请使用Windows Forms Timer.

您的设计师班:

partial class Form1
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.listBox1 = new System.Windows.Forms.ListBox();
        this.timer1 = new System.Windows.Forms.Timer(this.components);
        this.SuspendLayout();
        // 
        // listBox1
        // 
        this.listBox1.FormattingEnabled = true;
        this.listBox1.Items.AddRange(new object[] {
        "q",
        "w",
        "e",
        "r",
        "t",
        "y",
        "u",
        "sfdgsdf",
        "gf",
        "gsd",
        "fgs",
        "dfg"});
        this.listBox1.Location = new System.Drawing.Point(170, 200);
        this.listBox1.Name = "listBox1";
        this.listBox1.Size = new System.Drawing.Size(120, 95);
        this.listBox1.TabIndex = 0;
        // 
        // timer1
        // 
        this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(570, 502);
        this.Controls.Add(this.listBox1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.ListBox listBox1;
    private System.Windows.Forms.Timer timer1;
}

您的表单类:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        removeItems();
        if (listBox1.Items.Count == 0)
        {
            timer1.Stop();
        }
    }

    void removeItems()
    {
        MessageBox.Show("Hello from the removeMethod");
        listBox1.Items.RemoveAt(0);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1.Start();
    }
}