|
-
May 26th, 2009, 10:07 AM
#1
.Net ComboBox - Disabling selecteditem change
Hey,
I have a problem. I have a combobox that displays an arbitrary number of items. Lets say the names are ID0, ID1, ID2 (Displayed in the combobox.)
Now, when I have it's DropDownStyle property set to DropDown I can edit the text, but the SelectedItem is null anytime I enter text. Even if I write the same exact name it does not select it again.
What I want to do is for it to disallow this change of selecteditem, as the reason I want the user to enter text in the ComboBox is to change the ID property of the selecteditem, which obviously is harder if SelectedItem is set to null.
I seem to remember NOT having this problem a while ago, does anyone know what kind of settings I messed up?
-
May 26th, 2009, 12:14 PM
#2
Re: .Net ComboBox - Disabling selecteditem change
Hi,
Well the problem is that SelectedIndexChanged event of combobox does not launch when you edit the TextBox part of combobox. But if you try to get SelectedIndex, it still returns -1, meaning that no item is selected.
I did take a look of the problem and got it to work, but the solution is not pretty, but works nevertheless. Maybe someone can show how this problem could be solved 'the right way'?
Okay, here's the solution. If you have an item selected in combobox and start to edit its text value, when the TextUpdate-event triggers first time, you can get the selected index. Store that value to variable. Now when you press the Enter-key, get the value you have stored, and if it isn't -1, update the combobox item. Below is a code sample:
Code:
...
// store combobox selected index value here
private int _cmbSelectedIndex = -1;
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
// get combobox selected index value
if (comboBox1.SelectedIndex != -1)
_cmbSelectedIndex = comboBox1.SelectedIndex;
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (_cmbSelectedIndex != -1)
if (e.KeyCode == Keys.Enter)
comboBox1.Items[_cmbSelectedIndex] = comboBox1.Text;
}
...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|