DropDownList Incorrect SelectedIndex - c#

DropDownList control is returning the wrong item.
My code performs a specific action with the SelectedItem when DropDownList.SelectedValue = -1.
When testing the code, I pick item A at index = 2. The resulting DropDownList.SelectedItem = "A". Good so far.
But I pick item B at index = 3. The resulting DropDownList.SelectedItem = "A". According to the debugger, DropDownList.SelectedIndex = 2 in both cases.
What causes the SelectedIndex to always take on the same value?
Note: When I pick items C through Z, they return the proper SelectedText and SelectedIndex.
if(Int32.Parse(dropdown.SelectedValue).Equals(-1))
{
// Do something with the selected item
DoThis(dropdown.SelectedItem.ToString());
}

When several items of a DropDownList have the same value, selecting any of them will turn out as if the first item with that value was selected. You should modify the duplicate values to make each one unique.

Related

ComboBox doesn't load blank value when using ComboBox.SelectedItem = -1

I have a comboBox which correctly loads the List of data that I've queried from the DB, my only issue is that I can't seem to make it load blank and force the user to select from the list (which then pushes the actions under the SelectedIndexChanged() method). Through my searches, I've seen where I can simply change the SelectedItem value to -1, and that should load the comboBox on a null choice, but when I use this code I see no difference. The comboBox still loads the list correctly, but the first entry in the list is still displayed.
private void loadPatientList()
{
comboBox_PatientSelect.DataSource = patientList.Distinct().ToList();
comboBox_PatientSelect.DisplayMember = "displayFullName";
comboBox_PatientSelect.ValueMember = "patientID";
comboBox_PatientSelect.SelectedItem = -1;
}
I appreciate any help - and will be happy to provide more information if needed. Thank you in advance!
The property you're looking for is SelectedIndex. So make it comboBox_PatientSelect.SelectedIndex = -1;
From MSDN:
This property indicates the zero-based index of the currently selected item in the combo box list. Setting new index raises the SelectedIndexChanged event.
SelectedIndex, SelectedValue, and FormattingEnabled are related as follows:
If FormattingEnabled is false, SelectedIndex will not be set to -1 when SelectedValue is blank.
If FormattingEnabled is true, SelectedIndex will be set to -1 when SelectedValue is blank.
NOTE:
To deselect the currently selected item, set the SelectedIndex to -1. You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item.

Struct & Enum, Combobox.SelectedItem

The program is a minidatabase-ish thing for product ordering purposes, where I keep the unique orders in a struct, and the productNames in an enum (for practice basically). I only have 3 productnames (Product0, Product1, Product2), and they are added to a combobox (cbo_productNameEdit.DataSource = Enum.GetNames(typeof(productNames));).
Anyway, after saving an order, I want this combobox to change it's selected item to the saved product's name, but it fails to do so. I checked it with a MessageBox, to see if it didn't store it properly...
MessageBox.Show(Orders[cbo_productID.SelectedIndex].productName.ToString());
cbo_productNameEdit.SelectedItem = Orders[cbo_productID.SelectedIndex].productName;
... the messagebox returned Product2, which is indeed the correct one, but the selected item stayed at Product0.
One thing you could do to solve it is to set the SelectedIndex instead of SelectedItem property on the combobox. By default Enums are 0 based integers, so the index will corespond to the value of the enum.
cbo_productNameEdit.SelectedIndex = (int)Enum.Parse(typeof(productNames),
Orders[cbo_productID.SelectedIndex].productName.ToString());
Because you used .DataSource property for filling ComboBox with items
You need to use .SelectedValue for setting selecting item
cbo_productNameEdit.SelectedValue = Orders[cbo_productID.SelectedIndex].productName;
From MSDN: ComboBox.SelectedValue

SelectedItem of a variable combobox

There is a combobox which i fill with this loop
foreach (Machine.Types machine in machineList)
{
cbMachineGUI.Items.Add(machine);
}
after that i want the selected index to be one specific machine.
string machineComboBox = SettingsManager.getParameter("MachineType");
cbMachineGUI.SelectedItem = machineComboBox;
The parameter is correct and set, but the selecteditem of the combobox is always nothing.
if i set the machines in the properties of the combobox (not via the loop) it works. but i need the combobox to be variable.
any suggestions?
The problem is that what you put in Items and what you set SelectedItem to are different types.
You are filling the Items collection with Machine.Types instances, and setting SelectedItem to a string instance.
Using IndexOf like other answers suggest will not help, as this will not do anything that setting SelectedItem does not already do. It still won't find machineComboBox in the Items collection, just like it can't find it now.
You need to use matching types, so do one of these things (depending on how else you use the values in the combobox):
Convert Machine.Types to a string when filling the collection:
cbMachineGUI.Items.Add(machine.ToString());
Convert machineComboBox into an instance of Machine.Types that will match the one in Items when setting SelectedItem - how to do it depends on what Machine.Types is
Find the correct item yourself when setting SelectedItem:
cbMachineGUI.SelectedItem = cbMachineGUI.Items
.OfType<Machine.Types>()
.FirstOrDefault(item => item.ToString() == machineComboBox);
Either way, you must make a conversion between these two types somewhere.
Instead of setting SelectedItem, I suggest you find the item's index and set the selected index.
Something like this:
string machineComboBox = SettingsManager.getParameter("MachineType");
int itemIndex = cbMachineGUI.Items.IndexOf(machineComboBox);
cbMachineGUI.SelectedIndex = itemIndex;
You could try the following:
cbMachineGUI.SelectedIndex = cbMachineGUI.Items.IndexOf("MachineType"); // or whatever you want to select
It could be possible that the item you are trying to set doesn't present in combobox item list and since you haven't actually selected anything it sets to nothing. To check if the item does exist do below
string machineComboBox = SettingsManager.getParameter("MachineType");
if(cbMachineGUI.Items.IndexOf(machineComboBox) >= 0)
cbMachineGUI.SelectedItem = machineComboBox;
Quoting from MSDN documentation:
When you try to set the SelectedItem property to an object, the
ComboBox attempts to make that object the currently selected one in
the list. If the object is found in the list, it is displayed in the
edit portion of the ComboBox and the SelectedIndex property is set to
the corresponding index. If the object does not exist in the list, the
SelectedIndex property is left at its current value.The ComboBox class
searches for the specified object by using the IndexOf method.
Check ComboBox.SelectedItem for more information.

How to display blank item in the combobox?

For a Combobox, I am getting a list of values from the System.Collections.ObjectModel.Collection.
I am assigning the values like this:
this.cmbSqlServer.DataSource = this.SqlInstancesCollection;
I don't want to see the first item in the list in the Combobox, unless I selected it.
How do I display a blank field in the Combobox when nothing is selected?
If I understand correctly you just need to reset the SelectedItem. Just set SelectedIndex to -1.
this.cmbSqlServer.DataSource = this.SqlInstancesCollection;
this.cmbSqlServer.SelectedIndex = -1;

ListBox SelectedIndex returning wrong value

So I have an unbound ListBox populated with ListBox items with values such as:
new ListItem("Item1", "1")
new ListItem("Item2", "2")
new ListItem("Item3", "0")
new ListItem("Item4", "0")
new ListItem("Item5", "0")
A delete button should allow a user to delete a ListItem. However, whenever the user tries to delete an item with a value of zero, only the topmost 'zero' item is selected. In the example above, if 'Item5' was selected and delete was clicked, 'Item3' would be given the boot. Items with proper numbered values behave appropriately. Any idea why this might be happening, or did I answer my own question by typing it out (perhaps ASP.net can't differentiate between items with identical values)?
Any help would be greatly appreciated. Many thanks!
Edit: To clarify, items with values of zero are removed differently than items with other values. Ie: If an item has a non-zero value, it is removed by value. If it has a value of zero, it is removed by it's ListBox index, but that index is always being returned as the index directly under the last non-zero value.
You found the solution yourself. If you query the item by value, then the first item with that value will be returned.
Instead of removing by value, remove by the index:
myDropDown.Items.RemoveAt(0);
ListControl.Items.FindByText and ListControl.Items.FindByValue are only going to return a single ListItem, and I assume the first one they find.
If you wanted to handle your situation with multiples of the same value, then you'd likely have to write some loop to find and remove them all.
Your list items should have unique values. Asp.net only posts back the value selected for the list box so the server will be unable to tell which actual item it is so it just grabs the first match.
I would suggest looping through the collection and deleting the items, like this:
for (int i = 0; i < DropDownList1.Items.Count; i++)
{
ListItem item = DropDownList1.Items[i];
if (item.Value == "0")
DropDownList1.Items.RemoveAt(i);
}

Categories