[英]How to remove items in listbox that was randomly selected using timer
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
timer2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
int a = int.Parse(label3.Text)
+ 1;
label3.Text = a.ToString();
if (label3.Text == "10")
{
listBox1.Items.Add(label1.Text);
label3.Text = "0";
}
}
private void timer2_Tick(object sender, EventArgs e)
{
Random rnd = new Random();
int num = rnd.Next(1, listBox2.Items.Count);
label1.Text = num.ToString();
if (label3.Text == "10")
{
listBox1.Items.Add(label1.Text);
listBox2.Items.Remove(label1.Text); //this line of code isnt working. It doesnt delete anything.
}
}
我想發生的是我的label1將使用timer1混洗listbox2中的所有項目(1-10),然后,如果計時器達到10秒,listbox1將在其項目上添加label1最后一個數字,listbox2將其刪除。 它工作正常,但不會刪除listbox2中的內容
您可以使用:
int i = listBox2.Items
.Cast<ListBoxItem>()
.ToList()
.FindIndex(x=>x==label1.Text);
listBox2.RemoveAt(i);
更新:
Random rnd = new Random();
private void timer2_Tick(object sender, EventArgs e)
{
int num = rnd.Next(1, listBox2.Items.Count);
label1.Text = num.ToString();
if (label3.Text == "10")
{
listBox1.Items.Add(label1.Text);
listBox2.Items.Remove(label1.Text); //this line of code isnt working. It doesnt delete anything.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.