ListBox SelectedIndex returning wrong value - c#

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);
}

Related

How to Remove the selected index of a DropDownList?

I have an ASP.Net web for that inserts values into a database, I want to reset the selected items in the dropdownList, how do I do it properly?? I know with textBoxes I can use TextBox1.Text = String.empty but it doesnt seem to work with the dropdownLists
If you want to clear all Items means you can use
aspDrop.Items.Clear(); // whill clear all the list items
If you want to change the selected index means you have to use
aspDrop.SelectedIndex = someIndex; // where index must be in the list
Or even you can use .Insert() method to insert an item to a particular index and make it as selected item.
For DropDownList it would be better to first add an empty string at first position of the DropDownList by using yourDropDownList.Items.Insert method and then select it. Something like this:
yourDropDownList.Items.Insert(0, new ListItem(string.Empty, string.Empty));
yourDropDownList.SelectedIndex = 0;
Well if you want to clear dropdownList fully so you can clear it's items source such in this way:
ddItems.Clear();
But if you only want to clear selected dropdownListItem than S.Akbari solution:
ddItems.Items.Insert(0, new ListItem(string.Empty, string.Empty));
ddItems.SelectedIndex = 0;
I guess, everyone has given answers. But remember one thing to do as follows:
AppendDataBoundItems="False"
Set it to false as this will cause the rebound data to be appended to the existing list which will not be cleared prior to binding. The above is applicable when data is bound to the DropDownList. The rest will be done clearing it.

DropDownList Incorrect SelectedIndex

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.

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 exchange selected item in a list box winform

i'm trying to change 'selectedItem' in the list box, but 'selectedItem' is staying as is even though i create a new item with different data. appreciate your help
this.listBox1.SelectedItem = new ListBoxItem(m_CurrentItem);
//next line operate the event list item changed
this.listBox1.Items[index] = this.listBox1.SelectedItem;
I think you're doing the operations in the reverse order ^^
You should first add the new item in the list box with
this.listBox1.Items.Add(YourNewItem);
Then you can select the newly inserted item with
this.listBox1.SelectedItem = YourNewItem;
Or, since the .Add Method adds the element in the last position of the Items array, you can use
this.listBox1.SelectedIndex = this.listBox1.Items.Count - 1
See this article for reference on the ListBox.SelectedItem Property: http://msdn.microsoft.com/it-it/library/system.windows.forms.listbox.selecteditem(v=vs.110).aspx
:)

Cannot select multiple items in a dropdownlist

My C# ASP.NET web site has a weird problem.
I set a selected value for a dropdownlilst based on a value from a stored procedure output parameter like this:
this.myDropDown.SelectedValue = cmd.Parameters["#SourceID"].Value.ToString().Trim();
For some reason, I get a "Cannot have multiple items selected in a dropdownlist" error on this line of code. I've stepped through the code and searched for other references to this dropdownlist, commented the references out, and tried again.
Nope, still doesn't work.
The only way the page works is if I comment out the above line of code. Any ideas why this would be a problem?
SourceID is always an integer and exists in the list of selections. I've verified (by stepping through the code) that the selectedValue is always numeric, and never changes between the time this line executes and the time the page finishes loading.
Thoughts?
This would occur if you had two items in the DropDownList with the same Value.
If you do mean to select multiple items, you need to use ListBox control with SelectionMode="Multiple" set.
You have 2 items with the same value.
You can solve it:
1) Find Items by value to list.
2) Get first item index.
3) Select item by index.

Categories