I am trying to add a tag ID (RFID) to a listbox and then remove it after 30 seconds. 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). Declare the ExpiringItem class to store the time the entry was added. In your timer_click event check for expired items and remove.
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
lstTagsHold.Items.Add(new ExpiringItem(txtTagID.Text));
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.