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
Related
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"));
}
I am trying yo create a method that will take a value of one list box and will also be taken out of another list box at the same index. I am just a beginner to C# which is why I am having this problem. Thanks in advance for any help
if (lstCheckoutProduct.)
{
lstCheckoutProduct.Items.Remove(lstCheckoutProduct.SelectedItem);
int productIndex = lstCheckoutProduct.Items.IndexOf(lstCheckoutProduct.SelectedIndex);
lstCheckoutPrice.Items.Remove(productIndex);
}
else
{
lstCheckoutPrice.Items.Remove(lstCheckoutPrice.SelectedItem);
int priceIndex = lstCheckoutPrice.Items.IndexOf(lstCheckoutPrice.SelectedIndex);
lstCheckoutPrice.Items.Remove(priceIndex);
}
You need to get the SelectedIndex before removing the items. Also I assume your first line should check if the listbox is focused
And if you want to remove an item at a specific index you need to use RemoveAt instead of Remove.
if (lstCheckoutProduct.IsFocused)
{
int productIndex = lstCheckoutProduct.SelectedIndex;
lstCheckoutProduct.Items.Remove(lstCheckoutProduct.SelectedItem);
lstCheckoutPrice.Items.RemoveAt(productIndex);
}
else
{
int priceIndex = lstCheckoutPrice.SelectedIndex;
lstCheckoutPrice.Items.Remove(lstCheckoutPrice.SelectedItem);
lstCheckoutProduct.Items.RemoveAt(priceIndex);
}
EDIT: The first line is just a guess as you left it out in your question. Note that IsFocused will be false if the user has clicked a "Remove"-button (and thereby focussed the button instead of the listbox) to call this method.
EDIT: and you can reduce the code to this:
int index = lstCheckoutProduct.IsFocused ? lstCheckoutProduct.SelectedIndex : lstCheckoutPrice.SelectedIndex;
lstCheckoutProduct.Items.RemoveAt(index);
lstCheckoutPrice.Items.RemoveAt(index);
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;
}
I have a windows forms DataGridView, where I have data and a checkbox for each row.
I will select check box for a particular row and all the selected rows will be populated in another page.
if (grdEmp.Rows.Count > 0)
{
var selectedEmpIDs= from DataGridViewRow coll in grdEmp.Rows
where Convert.ToBoolean(coll.Cells["Select"].Value) == true
select coll;
if (selectedEmpIDs.Count() > 0)
{
foreach (DataGridViewRow row in selectedEmpIDs)
{
selectedEmp+= row.Cells["EmpId"].Value + ",";
}
}
}
This works good only for one page.
When I navigate to another page, and click the selected rows, the previous one goes off.
How do I resolve it.
Thanks
cmrhema
Note :Sorry for the confusion, When I meant it works good for a page, I meant paging.
I think I need to add more inputs,
There are 10 pages in the gridview.
I select the first record from each page of the gridview, one after another by clicking next page( Page next button).
But only the record that was selected the last is getting displayed and others and ignored off.
What could be the prblm
You can use a List or Dictionary or any other collection type globally, using Program.cs or using a static class. And store the selected rows into the list before you leave the page.
Rather than using a comma delimited string string for your list of ids you can instead use a List.
Your code will then become something like this:
if (grdEmp.Rows.Count > 0)
{
var selectedEmpIDs= from DataGridViewRow coll in grdEmp.Rows
where Convert.ToBoolean(coll.Cells["Select"].Value) == true s
select coll;
if (selectedEmpIDs.Count() > 0)
{
foreach (DataGridViewRow row in selectedEmpIDs)
{
if (!listOfIds.Contains((int)row.Cells["EmpId"].Value))
{
listOfIds.Add(((int)row.Cells["EmpId"].Value));
}
}
}
}
You will need methods to remove items from this list so adding event handlers for the checkbox selected event will probably work better.
The List object itself can simple live as a class level object of the form that containst your DataGridView.
This gets a little bit more complicated if you are managing your paging across forms, but the same principles of maintaining a list of selected ids applies.
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 ;)