determine if item is selected in C# ComboBox - c#

I am developing a windows forms application and load the list from this code:
private void showList()
{
TeamTableAdapter teamAdapter = new TeamTableAdapter();
lstTeamName.DataSource = teamAdapter.GetTeamsActive();
lstTeamName.DisplayMember = "TeamName";
lstTeamName.ValueMember = "TeamID";
}
I want to enable a button if the user selects one of the items. What event should I put the code into. I the following code but the event seems to fire before the user clicks on the list.
private void lstTeamName_Click(object sender, EventArgs e)
{
if (lstTeamName.SelectedIndex > -1)
btnImportXML.Enabled = true;
}
I moved my code to the SelectedIndexChange event but it still fires before the user selects an item and the selectedIndex is 0.

You dont want to bind to the Click event but to the SelectedIndexChanged event. You should be able to accomplish this by simply double clicking on the Control in designer.

I would agree that you don't want to bind to Click as that will likely fire too early.
I recommend you look into the DropDownStyle property. http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle(v=vs.110).aspx. If you set that to DropDownList then the SelectedItemChanged will fire and SelectedIndex could be > -1
If you leave it as the default DropDown then you may want to use TextChanged and check the Text property.

Related

Combobox selected index changed event not fired in code

I am working on a Windows Forms application and I have a combobox named cmbCountry. I am binding this combobox to a list which contains names of countries. Following is the code to populate the combobox.
cmbCountry.DataSource = lstcountry;
Next I want to set selected item as "United States of America". so I added the following code
cmbCountry.SelectedItem="United States of America";
I want to do some code on selection change event of this combobox.
private void cmbCountry_SelectionChangeCommitted(object sender, EventArgs e)
{
\\some code
}
This method is suppose to be call when I set the selected item. But it is not getting called. However when I select "United States of America" from UI part(Design Part) this event getting called. I want to get called this event when I set the selected item.
SelectionChangeCommitted fires when the user manipulates via the UI.
SelectionChangeCommitted is raised only when the user changes the
combo box selection. Do not use SelectedIndexChanged or
SelectedValueChanged to capture user changes, because those events are
also raised when the selection changes programmatically.
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectionchangecommitted.aspx
Use SelectedIndexChanged or SelectedValueChanged
Change your event to SelectedIndexChanged:
private void cmbCountry_SelectedIndexChanged(object sender, EventArgs e)
{
\\some code
}
And change the event handler (which may be automatically generated):
this.cmbCountry.SelectedIndexChanged += new System.EventHandler(this.lstResults_SelectedIndexChanged);

C# autocomplete combobox trigger SelectionChangeCommited

I'm having problems with the autocomplete property of a combobox. I want to trigger the SelectionChangeCommited event every time I choose an item using the autocomplete but it's not working. The only way the event is triggered is when I use the mouse click and select an option or when the combobox is focused and I use arrow keys on the keyboard. How do I achieve this behaviour using the autocomplete property?
My combo has these properties set:
AutoCompleteMode = SuggestAppend
AutoCompleteSource = ListItems
FormattingEnabled = True
The items in my combo are set with a datasource.
Any ideas?
Thanks
If you mean that you want it to register a change when you start typing:
Call the SelectionChangeCommited event from the TextChanged event.
If you've never done this, the most basic example I could find was on the .net forums here. Granted, the methods shown there are generalities, but is very simple to understand and apply to your code.
EDIT FIXED (as of most recent comment):
Still tie the events together, but instead of using TextChanged, which would occur ever time you type, use the SelectedIndexChanged, which occurs when you use the mouse to select an auto suggested item.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1_SelectionChangeCommitted(sender, e);
}
you canuse a trick and call comboBox1_SelectionChangeCommitted
in Validated event
when ever text in combobox changes and user leave the combo box it will be fired
private void comboBox1_Validated(object sender, EventArgs e)
{
comboBox1_SelectionChangeCommitted(sender, e);
}

Disabling the onSelectedIndex changed event of WPF dropdown combo on navigating through arrrow keys

When I am having a value item selected in my WPf DropDown Combo Box then navigating using keys Left and right arrow keys result in firing of selected changed event for each item.
How to overcome this problem
The most easy and suitable way I found to overcome this problem is as follows:
rather than using SelectedIndexChanged event I used on DropDownClosed event and all code that is wriiten earlier inside selected index changed moved to this event under a if condition that checks whether a item is selected or not. Like this.
private void OnCmbOperatorsListDropDownClosed(object sender, EventArgs e)
{
if (cmbOperatorsList.SelectedIndex != -1)
InsertText(cmbOperatorsList.SelectedValue.ToString());
//Do whatever u want with selected item
}
So in this way when i navigate through Arrow keys SelectedIndexChagned event will not fired or since i haven't used that event so it will not create any problem.
As per my knowledge this is not possible straight away. I could have implemented this in a kind of "selection simulated" manner.
Handle arrow keys on combobox dropdown in PreviewKeyDown event by setting e.Handled = true. So that usual navigation based selection wont happen.
Inthese handlers based on Keys, change the Background and Foreground of the previous or next item from the drop down list so that it will look as if its selected and highlighted.
Then perform selection of the item which curently has the "simulated selection background - foreground" when dropdown closes. After dropdown closure, revert the background and foreground style.
But thats just my way of doing it.
You can use the PreviewKeyDown event like
private void combo_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key.Equals(Key.Left) || (e.Key.Equals(Key.Right)))
{
((ComboBox)sender).SelectionChanged -= combo_SelectionChanged;
}
}
and if u want to attach that event you can add this PreviewMouseDown event.
This is what i tried and may not be a proper method of doing such cases

Detect if mouse click hits a item not in listbox [C#]

If the user click on a item in the listbox, the listboxItems_SelectedIndexChanged is called. But, even if the user miss an item and randomly clicks inside the listbox (not on items) the listboxItems_SelectedIndexChanged is still called.
How can I change this? I only want action on item click.
Note: removing the ability to navigate the application with keyboard is not a option.
I guess that in some cases you don't have enough list items in your control, therefore you have some space that you can click on and then SelectedIndexChanged is fired.
I guess you cannot dynamically resize the control to always fit the number of list items or else you wouldn't be asking this question.
Now, what should happen when the user click (selects) the same list item? Should some logic happen even though the selected index is the same (so when it was clicked the first time the same logic happend)?
If you require that selecting the same index more than once should be ignored then you could use the following hack:
Keep a variable at the form scope (the form containing the listbox control) and each time the selection index changes set that variable. Then use it later to check if the same selection has been made to ignore handling the event. Here is an example:
private int _currSelIdx = -1; // Default value for the selected index when no selection
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == _currSelIdx)
return;
Console.WriteLine(listBox1.SelectedIndex);
_currSelIdx = listBox1.SelectedIndex;
}
It ain't pretty, but hey...whatever works!
Maybe SelectedIndexChanged is not the right place to put your logic, since it is triggered even when you change the selection with the keyboard.
I would use MouseClick instead, checking if the click occurred over the selected item, i.e. something like this:
private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
if (listBox1.SelectedIndex < 0 || !listBox1.GetItemRectangle(listBox1.SelectedIndex).Contains(e.Location))
MessageBox.Show("no click");
else
MessageBox.Show("click on item " + listBox1.SelectedIndex.ToString());
}
This link may help, instead of double click, implement the same for single click
i want to detect an item double click in a winforms listbox control. [how to handle click on blank area?]

Combobox and autocomplete in C#

i have small problem with autocomplete option in combobox. Everything is working correct, except that i want to work it diffrent :)
When I start typing in combobox, autusuggest working the way i like :
But when i first open combobox, and then start typing i get something like that:
What's more i can't pick item from autosuggest combobox, only from this list under.
AutocompleteMode is SuggestAppend
I'd like to have autosuggest like on the first picture, and in situations like picture 2, this first combobox list should be closed somehow..
I had the same problem and solved it this way:
private void comboBox_DropDown(object sender, EventArgs e)
{
ComboBox cbo = (ComboBox)sender;
cbo.PreviewKeyDown += new PreviewKeyDownEventHandler(comboBox_PreviewKeyDown);
}
private void comboBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
ComboBox cbo = (ComboBox)sender;
cbo.PreviewKeyDown -= comboBox_PreviewKeyDown;
if (cbo.DroppedDown) cbo.Focus();
}
Once the user clicks on the DropDown button PreviewKeyDown event is attached to that ComboBox. When user starts typing, freshly added event is triggered. In that event we check if ComboBox is DroppedDown, if it is, focus that ComboBox. On ComboBox focus DropDown disappeares and that's it.
What about using the DropDown and DropDownClosed events to disable or change the auto-complete mode?
I was having exactly the same problem.
I tried the DropDown and DropDownClosed events to set the AutoCompleteMode property to none and suggest.
In this situation the SelectedIndexChanged event does not get fired after selecting an item with the mouse.
I was using the SelectedValue property in the SelectedIndexChanged event and this property is already changed at the moment the DropDownClosed event is triggered.
In my case I simply called the SelectedIndexChanged method from the DropDownClosed event to solve the problem.
Implement event on ComboBox KeyDown. It should look like this.
void cmbExample_KeyDown(object sender, KeyEventArgs e)
{
if ((sender as ComboBox).DroppedDown)
(sender as ComboBox).DroppedDown = false;
}
Have you tried the other possible values for AutoCompleteMode, which are Append, None, and Suggest? I think that what you are looking for is Suggest instead of AppendSuggest.
Here is some downloadable sample code illustrating the different modes, if you need it.
I also found the default UI implementation distracting as the two dropdowns fight for mouse control.
You want to hide the dropdown list when autocomplete suggestions are shown. There is a windows message that the combobox makes before showing the autocomplete suggestions. I chose to collapse the droplist in response to this message. It requires a small override of the combobox to achieve this:
Public Class Combobox2
Inherits ComboBox
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = 135 AndAlso DroppedDown Then 'WM_GETDLGCODE
DroppedDown = False
End If
MyBase.WndProc(m)
End Sub
End Class
void cmbExample_KeyDown(object sender, KeyEventArgs e)
{
cmbExample.DroppedDown = false;
}

Categories

Resources