[英]Add item to listbox and then remove after 30 seconds
I am trying to add a tag ID (RFID) to a listbox and then remove it after 30 seconds. 我正在尝试将标签ID(RFID)添加到列表框中,然后在30秒后将其删除。 What is the best way to do this?
做这个的最好方式是什么?
txtTagID.Text = s1.Replace(" ", "").ToLower();
if (lstTagsHold.Items.Contains(txtTagID.Text) == false)
{
lstTagsHold.Items.Add(txtTagID.Text);
}
尝试使用计时器控件(如果使用的是winforms)
// Declare the timer
private static System.Timers.Timer objTimer = new System.Timers.Timer(30000);
// Attach the event handler
objTimer.Elapsed += OnTimedElapsed;
private static void OnTimedElapsed(Object source, System.Timers.ElapsedEventArgs e)
{
lstTagsHold.Items.Remove(txtTagID.Text);
}
Drop a System.Windows.Forms.Timer on your form and set the interval to around 1 second (or less depending on accuracy required). 将System.Windows.Forms.Timer放在窗体上,并将时间间隔设置为1秒左右(或更短时间取决于所需的精度)。 Declare the ExpiringItem class to store the time the entry was added.
声明ExpiringItem类以存储添加条目的时间。 In your timer_click event check for expired items and remove.
在您的timer_click事件中,检查过期项目并删除。
class ExpiringItem
{
private string text;
public ExpiringItem(string text)
{
this.text = text;
this.Added = DateTime.Now;
}
public DateTime Added { get; private set; }
public override string ToString()
{
return text;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
for (int i = listBox1.Items.Count -1; i > -1; i--)
{
var exp = (ExpiringItem)listBox1.Items[i];
var timeVisible = DateTime.Now - exp.Added;
if (timeVisible.TotalSeconds > 30)
listBox1.Items.RemoveAt(i);
}
}
To add items to your ListBox do 要将项目添加到ListBox中,请执行以下操作
lstTagsHold.Items.Add(new ExpiringItem(txtTagID.Text));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.