C#:按下Enter键时更改DropDownList值(C#: Change DropDownList value when Enter key is pressed)

编程入门 行业动态 更新时间:2024-10-26 18:19:39
C#:按下Enter键时更改DropDownList值(C#: Change DropDownList value when Enter key is pressed)

我有一个带有DropDownList的Windows窗体,其中包含固定数量的项目。 当我按Enter键时,如何使DropDownList增量到下一个项目,当它到达项目的末尾时,返回到第一个项目。

I have a windows form with a DropDownList with a fixed number of items. How do I make the DropDownList increment to the next item when I press Enter and when it reaches the end of the items, return to the first item.

最满意答案

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

更多推荐

本文发布于:2023-08-07 05:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1461186.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按下   Enter   DropDownList   pressed   key

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!