2010-03-25 83 views
1

我有一個帶有固定數量項目的DropDownList的窗體窗體。當我按Enter鍵時,如何使DropDownList增量到下一個項目,當它到達項目的末尾時,返回到第一個項目。C#:按下Enter鍵時更改DropDownList值

+0

如果您打算在多個地方使用此功能,則應該考慮將其作爲自定義用戶控件。 – eschneider 2010-03-25 18:47:21

+0

這些答案可以正常工作,但我已經設置了AcceptButton變量:this.AcceptButton = SubmitButton; 使用此設置,當按Enter鍵時不會觸發keydown事件。有沒有解決的辦法?我想要進入既觸發SubmitButton並增加組合框中的值。 – Addie 2010-03-25 19:36:06

+0

我不認爲你可以。 – eschneider 2010-03-25 20:02:04

回答

2
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      this.KeyPreview = true; 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      this.comboBox1.DataSource = CreateItems(); 

     } 


     private List<string> CreateItems() 
     { 
      List<string> lst = new List<string>(); 
      lst.Add("One"); 
      lst.Add("Two"); 
      lst.Add("Three"); 
      lst.Add("Four"); 
      return lst; 
     } 

     private void comboBox1_KeyDown(object sender, KeyEventArgs e) 
     { 
      if (e.KeyData == Keys.Enter) 
      { 
       if (comboBox1.SelectedIndex == comboBox1.Items.Count-1) 
       { 
        comboBox1.SelectedIndex = 0; 
        return; 
       } 

       if (comboBox1.SelectedIndex >=0 & comboBox1.SelectedIndex< comboBox1.Items.Count-1) 
       { 

        comboBox1.SelectedIndex = comboBox1.SelectedIndex+1; 
       } 

      } 
     } 

    } 
} 
+0

您正在尋找'else'關鍵字和'++'簡寫。 – SLaks 2010-03-25 14:48:09

+0

因爲我設置了AcceptButton變量,所以當我按Enter時不會觸發keydown事件。我如何解決這個問題?看到我上面的評論。 – Addie 2010-03-25 19:37:32

2

您需要處理KeyDown事件並更改SelectedIndex屬性。