簡體   English   中英

C#:按下Enter鍵時更改DropDownList值

[英]C#: Change DropDownList value when Enter key is pressed

我有一個帶有DropDownList的Windows窗體,其中包含固定數量的項目。 當我按Enter鍵時,如何使DropDownList增量到下一個項目,當它到達項目的末尾時,返回到第一個項目。

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

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;
                }

            }
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM