I'm creating an application with a ListBox. I want the user to be able to click on it, start typing, and see their text appear in that item. Below is a simplified version that almost works:
using System.Windows.Forms;
namespace ListboxTest
{
public partial class ListboxTest : Form
{
InitializeComponent();
listBox1.Items.Add("");
listBox1.Items.Add("");
listBox1.KeyPress += new KeyPressEventHandler(ListBoxKeyPress);
}
private void ListBoxKeyPress(object sender, KeyPressEventArgs e)
{
ListBox lbx = (ListBox)sender;
if (lbx.SelectedIndices.Count != 1)
return;
int temp = lbx.SelectedIndex;
string value = lbx.Items[temp].ToString();
value += e.KeyChar;
lbx.Items[temp] = value;
}
}
When the ListBox is selected, the user can start typing and see the text show up. Everything works as expected until two things happen:
- User switches from one item to another (click into a different input or use the up/down arrows), followed by
- User presses the key corresponding to the first character in the unselected item's name.
From then on, whenever the user presses that key (in my case, a '1'), the ListBox's selected item changes. With only two items (both starting with '1'), pressing '1' causes the ListBox to switch the selected item from index 0 to index 1 (and vice-versa).
I've experimented a bit, and this is what I've found.
This only occurs when I press '1'. No other digit, numeral, or punctuation mark causes this.This will happen with any character that the ListBox item begins with.- If the ListBox has more than two items, it will cycle through all previously entered elements with the same start character. Items that have never been selected are skipped.
What I've tried:
- Clearing the selected indices by
ListBox.SetSelected(int index, bool selected)
- Clearing the selected indices by
ListBox.ClearSelected()
- Setting
Listbox.SelectionMode
toSelectionMode.One
I am using VS 2015 Professional, Windows 7 SP1 (x64), C# 6.0, and targeting .NET 4.6.1.
So, my question: what's happening and how do I fix it?