Remove selected items from combo box - c#

I wish to remove selected item from combo box
The selected items from combo box are dispayed in a data grid view and i dont wish to reselect the same item from the same combo box .
How can this be done ? , plz help
combobox1InHouseStatus.Items.RemoveAt(combobox1InHouseStatus.SelectedIndex);
I tried this but it isnt working !!!

I needed to do the same thing, but in my case multiple items could be selected. Here's the code I used:
int x = this.aComboBox.SelectedItems.Count;
while (x >= 1) {
this.aComboBox.Items.Remove(this.aComboBox.SelectedItems(x - 1));
x -= 1;
}

Related

C# Find the Selected State of all items in a ListBox

I have found many examples on how to find the selected items in a listbox and how to iterate through a listbox;
for(int index=0;index < listBox1.Items.Count; index++)
{
MessageBox.Show(listBox1.Items[index].ToString();
}
or
foreach (DataRowView item in listBox1.Items)
{
MessageBox.Show(item.Row["ID"].ToString() + " | " + item.Row["bus"].ToString());
}
While these methods work great for the selected items, what I have yet to figure out, or find, is how to get the selected state, selected and unselected, of every item in a listbox, as the above only gives the selected.
Basically, I need something like this;
for(int index=0;index < listBox1.Items.Count; index++)
{
if (index.SelectedMode == SelectedMode.Selected)
{
MessageBox.Show(listBox1.Items[index].ToString() +"= Selected";
}
else
{
MessageBox.Show(listBox1.Items[index].ToString() +"= Unselected";
}
}
I've found a snippet that said to use (listBox1.SelectedIndex = -1) to determine the selected state however I've not figured out or found how to build a loop around this to check each item in the listbox.
I've also read that I should put the listbox items into an array, but again nothing about getting the selected state of each item in the listbox.
I know I'll have to iterate through the listbox to accomplish what I'm needing, pretty sure it'll be one of the above loops, however I have yet to find how to extract the selected state of each item in the listbox.
I'm using VS2013, C# Windows Form, .NET Framework 4.0
Thanks in advance for any advice/direction.
This will get you the unselected items:
List<string> unselected = listBox1.Items.Cast<string>().Except(listBox1.SelectedItems.Cast<string>());
You can loop over that list like this:
foreach(string str in listBox1.Items.Cast<string>().Except(listBox1.SelectedItems.Cast<string>()))
{
System.Diagnostics.Debug.WriteLine($"{str} = Not selected");
}
I've made the assumption that you're using string as your item type. If you want to use something else then just replace string with your type and it should still work.
You then loop over the unselected items to do whatever you want with them then loop over listBox1.SelectedItems to do whatever you want with the selected ones.
You can use GetSelected method of the ListBox. It returns a value indicating whether the specified item is selected.
For example, the following code, sets the value of selected to true if the item at index 0 (the first item) is selected:
var selected = listBox1.GetSelected(0);
Example
Te following loop, shows a message box for each item, showing the item text and item selection status:
for (int i = 0; i < listBox1.Items.Count; i++)
{
var text = listBox1.GetItemText(listBox1.Items[i]);
var selected = listBox1.GetSelected(i);
MessageBox.Show(string.Format("{0}:{1}", text, selected ? "Selected" : "Not Selected"));
}

The value is not within the expected range

Can we render two UI element at same grid position in SelectionChanged event of a combo box.
The exact problem is i have grid and inside the grid there are two rows the first row will always show me a ComboBox(of which i was talking about line before) on selecting
different item will render different UI elemnts at same position in the second row of the grid.
So i tried to do the rendering of the UI element in the SelectionChanged event of the Combo.
But the problem happening is when i select the first element then it is displayed properly but when i try to select the second UI element to be rendered at same position on Combo selection change then it gives a warning
"the value is not within the expected range." at Line : "bigGrid.Children.Add(ck);"
My code to do this is:
Grid childGrid = createChildGrid();
Grid ck = new Grid(); //This ck will contain ComboBox at row zero and UI element at second row
ck.RowDefinitions.Add(new RowDefinition());
ck.RowDefinitions.Add(new RowDefinition());
int loopCount = 0; //This variable will help in changing the row index
if (loopCount == 0)
{
ComboBox cmb = new ComboBox();
//Here i add items in Combo:
foreach(string ccyp in attributeName)
{
if (ccyp != null)
cmb.Items.Add(ccyp);
}
cmb.SelectionChanged += (o, e) =>
{
txtblkName.Text = cmb.SelectedValue.ToString();
ck = generateUIElementCorrespondingTotxtLabelNameObtainedOnComboSelection(txtblkName.Text); //this function will return a grid containing the selected UI elemnt from combo box.
Grid.SetRow(ck, loopCount);
bigGrid.Children.Add(ck); //**THIS LINE GIVE EXCEPTION: "the value is not within the expected range."**
};
}
Grid.SetColumn(cmb, 1);
childGrid.Children.Add(cmb);
Grid.SetRow(childGrid, loopCount);
bigGrid.Children.Add(childGrid);
loopCount++;// I incrtease loop count so that on selection changed event of combo UI will be displayed on second row loopcount=1
EDIT: On debugging i get :The result of break point is : loopcount=1 (for rendering of combo item in second row)this " Grid.SetRow(ck, loopCount); bigGrid.Children.Add(ck);" and for combo box display loopcount= 0 (i mean here : "Grid.SetRow(childGrid, loopCount); bigGrid.Children.Add(childGrid); loopCount++;")
From question Silverlight: Value does not fall within the expected range exception
'This error can be caused when there are two elements being added with the same name.' What identifiers are added to the combo boxes?
If this is the problem, as suggested in the linked question, you could add a unique identifier to each combo box.

Combo Box Size Issue After All Items Are Removed

My application contains a ComboBox that the user can delete items from. When the program starts up it populates the ComboBox from a list of strings read in from a configuration file.
Here is the code to add items:
// version list is an array of strings
foreach (string version in versionList)
{
versionComboBox.Items.Add(version);
}
if (versionComboBox.Items.Count > 0)
{
versionComboBox.SelectedIndex = 0;
}
Here is a screenshot of the combo box after it's been populated:
If the user clicks the Delete button the program removes the selected item from the ComboBox using the following code:
if (versionComboBox.SelectedIndex >= 0)
{
versionComboBox.Items.Remove(versionComboBox.SelectedItem);
}
if (versionComboBox.Items.Count > 0)
{
versionComboBox.SelectedIndex = 0;
}
Here is a screenshot of the combo box after a few items have been removed:
The problem I am having is when the last item is removed the ComboBox resizes itself to the size it was when it was initially populated. There aren't any items in the ComboBox but it sizes itself as if there were.
Here is a screenshot after all the items have been removed:
As you can see the size is too big. I would think that after all the items were cleared it would look like the following:
Any ideas as to why this is happening?
Try to use this at the end of your code when you are filling the combobox items:
comboBoxNumTreno.IntegralHeight = true; // auto fit dropdown list
Then to clear it up:
comboBoxNumTreno.ResetText();
comboBoxNumTreno.Items.Clear();
comboBoxNumTreno.SelectedIndex = -1;
comboBoxNumTreno.DropDownHeight = 106; // default value
comboBoxNumTreno.IntegralHeight = false;
I know this is an old post, but it took me a long time to figure this out and I wanted to let anyone in the future know. After you clear your combo box just do a blank add items and it resets the height.
comboBox1.Items.Clear();
comboBox1.Items.Add("");
To clear your combo box you can add this:
if (versionComboBox.Items.Count == 0)
{
versionComboBox.Text = string.Empty;
versionComboBox.Items.Clear();
versionComboBox.SelectedIndex = -1;
}
Another approach is to manipulate the items in the data source and rebind the control each time (a lot less for you to worry about).
set DropDownHeight property to fix size
versionComboBox.DropDownHeight = 106; // default value

Setting default item in combo box

I have a function for setting items in a combobox and one item is to be set by default like
--SELECT LIST--
public void SetOperationDropDown()
{
int? cbSelectedValue = null;
if(cmbOperations.Items.Count == 0)
{
//This is for adding four operations with value in operation dropdown
cmbOperations.Items.Insert(0, "PrimaryKeyTables");
cmbOperations.Items.Insert(1, "NonPrimaryKeyTables");
cmbOperations.Items.Insert(2, "ForeignKeyTables");
cmbOperations.Items.Insert(3, "NonForeignKeyTables");
cmbOperations.Items.Insert(4, "UPPERCASEDTables");
cmbOperations.Items.Insert(5, "lowercasedtables");
//ByDefault the selected text in the cmbOperations will be -SELECT OPERATIONS-.
cmbOperations.Text = "-SELECT OPERATIONS-";
}
else
{
if(!string.IsNullOrEmpty("cmbOperations.SelectedValue"))
{
cbSelectedValue = Convert.ToInt32(cmbOperations.SelectedValue);
}
}
//Load the combo box cmbOperations again
if(cbSelectedValue != null)
{
cmbOperations.SelectedValue = cbSelectedValue.ToString();
}
}
Can anyone suggest a way to do this?
I've rewritten this answer to clarify some stuff.
First, the "default" text must be added as combo item as well.
Usage of combo.Text property just adds descriptive text to combobox which is "lost" first time user do something with a control.
If you like to permanently have "default" text in your combo, you must add it as an combobox item.
By the code you provided, just modify the
cmbOperations.Text = "-SELECT OPERATIONS-"; to
cmbOperations.Items.Insert(0, "-SELECT OPERATIONS-");
Note that this way you add the item "-SELECT OPERANDS-" to the 0th (read first) position in the list.
Also make sure that all your following items are increased by 1, because they are now moved by one space down in list.
Finally, put cboOperations.SelectedIndex = 0; line at the end of code. By doing so, you're telling combobox to display your "default" item initially when the form (or control) loads.
One more thing. I'm not pretty sure what do you want to achieve with the code beyond setting combo items, but if you like to check what user selected use cboOperations.SelectedIndex property which contains currently selected item in combo. You can add simple if(cboOperations.SelectedIndex == someIntValue){...}
The rest is your program logic ;)

listview checkbox checked row item

I want to reach checked rows item in ASP.Net Listview control.
For example:
if 3 Lines of Listview checked, I want to reach checked items value in listview.
How can I do this?
Thanks.
You can use listview property 'CheckedItems'.
You can get list of items which are checked using listview.CheckedItems. For the value in that item, based on the subitem index you need to fetch it. For ex.
ListView.CheckedListViewItemCollection checkedItems =
ListView1.CheckedItems;
foreach ( ListViewItem item in checkedItems )
{
value = item.SubItems[1].Text;
}

Categories