2016-04-08 205 views
0

如何自動選擇ListBox中的某個項目,然後將其設置爲TextBox中的文本,然後等待3秒鐘並移至下一行並重復?在列表框中循環並設置文本框文本

private void button2_Click(object sender, EventArgs e) 
{ 
    timer.Start(); 
} 

private void timer1_Tick(object sender, EventArgs e) 
{ 
    foreach (var item in listBox1.Items) 
    { 
     textBox2.Text = listBox1.Text;     
    } 
} 
+2

增量的'SelectedIndex'在'timer1_Tick'。您不需要在那裏進行循環,因爲您一次只需處理一個項目。 –

回答

1

timer1_Tick應該是這樣的:

public Form1() 
{ 
    InitializeComponent(); 
    timer1.Interval = 3000; 
} 
private void timer1_Tick(object sender, EventArgs e) 
{   
    Random rnd = new Random(); 
    int i = rnd.Next(0, listBox1.Items.Count - 1); 
    textBox2.Text = listBox1.Items[i].ToString();    
} 

編輯:

int i; 

private void timer1_Tick(object sender, EventArgs e) 
{    
    if (i > listBox1.Items.Count - 1) 
    { 
     i = 0;//Set this to repeat 
     return; 
    } 
    textBox2.Text = listBox1.Items[i].ToString(); 
    i++; 
} 

,還可以設置定時器的時間間隔,以3000

+0

這是完美的,但我如何使它不隨機? – Waypast

+1

@Waypast ...看到我編輯的答案。 –

+0

@Waypast ...再次看到我編輯的答案,看看如何通過在'if'語句中設置'i = 0;'來重複這個過程。 –

1

列表框具有很多有用的性質:

private void timer1_Tick(object sender, EventArgs e) 
{   
    textBox2.Text = listBox1.SelectedItem.ToString(); 
    listBox1.SelectedIndex = (listBox1.SelectedIndex + 1) % listBox1.Items.Count; 
} 

%是模運算,並返回所述除法的餘數。它確保始終返回0SelectedIndex - 1之間的值並使索引重複。

此外,如果未選擇任何項目,您將獲得SelectedIndex-1SelectedItem將爲null。因此,請務必通過設置適當的初始條件或添加檢查來避免這些情況。

例如爲:

if (listBox1.Items.Count > 0) { 
    if (listBox1.SelectedIndex == -1) { 
     listBox1.SelectedIndex = 0; 
    } 
    ... // code of above 
}