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.
+2
A:
You need to handle the KeyDown
event and change the SelectedIndex
property.
SLaks
2010-03-25 02:06:37
+2
A:
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;
}
}
}
}
}
eschneider
2010-03-25 02:25:10
You're looking for the `else` keyword and the `++` shorthand.
SLaks
2010-03-25 14:48:09
The keydown event is not triggered when I press enter because I've set the AcceptButton variable. How do I get around this? See my comment above.
Addie
2010-03-25 19:37:32