Clear the Selection of an Item in a ListBox C# - c#

I have a multi-select list box. When an item is selected a document is opened in a tab control. When the document is closed I want to un-select the item in the list box. I don't want it removed from the collection, I don't want to clear all selections. I just want to clear that particular selection.
In the OnRequestClose() method;
string itemName=workTab.DisplayName;
foreach (QResult r in FileListBox.SelectedItems)
{
If(r.FileName = itemName) //Clear the Selection
That is my approach but I can't seem to get the syntax and the examples I find are for clearing all or removing the selected items from the list.
Thanks for the help.

This should work:
foreach (var r in FileListBox.SelectedItems.Cast<QResult>().ToList())
{
if (r.FileName == itemName) //Clear the Selection
{
FileListBox.SelectedItems.Remove(r);
}
}

Have you tried:
string itemName=workTab.DisplayName;
var i=0;
while (i<FileListBox.SelectedItems.Count)
{
QResult r = FileListBox.SelectedItems [i]
if(r.FileName = itemName){
FileListBox.SelectedItems.Remove(r);
}
i++;
}

Related

How to keep selected item highlighted while searching in listbox in c# winforms?

I have a list box that is populated by some items, the form contains textbox and a list box. In the textbox user can search for specified entry in list box. Now if user types in some text in textbox then filtered listbox items is shown in list.
Now, Suppose if i have previously selected any item in listbox before search then if i search the list box my last selected element if it exists in filtered items is not shown highlighted.
How can i show my lasted selected item highlighed in filtered list if it exists in it.
Example - Before searching in listbox.
After searching the list my last selected item if exists in filtered list loses the display selection.
My code for searching listbox -
private void vmS_TextBox1_TextChanged(object sender, EventArgs e)
{
string keyword = this.iBoxEventlistSearchTextBox.Text;
lBox_Event_list.Items.Clear();
foreach (string item in sortedEventList)
{
if (item.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
{
lBox_Event_list.Items.Add(item);
}
}
}
Also i have selected index change event handler applied on this list box any i don't want to fire it again for filtered list view. I just only want to show it highlighted on filtered list.
Thankyou!
You can save the item that was selected before typing and the searching for it in the remaining items and then set the item selected if present.
private void vmS_TextBox1_TextChanged(object sender, EventArgs e)
{
string keyword = this.iBoxEventlistSearchTextBox.Text;
// Save the selected item before
var selectedItem = string.Empty;
if(lBox_Event_list?.Items?.Count > 0)
selectedItem = lBox_Event_list.SelectedItem;
lBox_Event_list.Items.Clear();
foreach (string item in sortedEventList)
{
if (item.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
{
lBox_Event_list.Items.Add(item);
}
}
// Search for it in the items and set the selected item to that
if(string.IsNullOrEmpty(selectedItem))
{
var index = lBox_Event_list?.Items?.IndexOf(selectedItem);
if(index != -1)
lBox_Event_list.SelectedIndex = index;
}
}

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

c# select listview item if two listviews contains it

In my program I have 2 listviews and 1 button.
When I press the button, every listview item in the first listview will be selected in the second listview. The items in the first listview always exist in the second listview, but not the other way around.
I'm having trouble with selecting the items in the second listview. I'm trying to get the index with IndexOf.
foreach (ListViewItem item in firstListView.Items)
{
int index = secondListView.Items.IndexOf(item);
secondListView.Items[index].Selected = true;
}
I always get an error that index is -1 when I click the button. And I don't understand what I'm doing wrong.
SOLUTION
So what I tried to do here finding an index of an item which belongs to a different listview, and it doesn't work like that. Even though the text in both listviews are the same, the listview items are not identically the same because they are reference types.
I was not able to use the Text property because items could have the same text. So the solution I had was putting an unique integer in the Tag property for each ListViewItem. Since integers are value types, I can use that integer to check whether the ListViewItem in the first listview is in the second.
// Loop through each item in the first listview
foreach (ListViewItem item1 in firstListView.Items)
{
// For each item in the first listview, loop through the second listview to find if it's there
foreach (ListViewItem item2 in secondListView.Items)
{
// Check if item1 is identical to item2 by looking at its tag
if (int.Parse(item1.Tag) == int.Parse(item2.Tag))
{
// The item has been found and will be selected!
item2.Selected = true;
}
}
}
You can use such linq query to select items of the second list which exist in the first list too:
var items = from i1 in listView1.Items.Cast<ListViewItem>()
from i2 in listView2.Items.Cast<ListViewItem>()
where i1.SubItems.Cast<ListViewItem.ListViewSubItem>()
.Where((s, i) => s.Text != i2.SubItems[i].Text).Count() == 0
select i2;
items.ToList().ForEach(x => { x.Selected = true; });
Note:
When to try to use secondListView.Items.IndexOf method to find an item which belongs to the firstListView you can not expect it to find the item. The item you are trying to find its index, doesn't exists in second listview's item collection. You should find items using Text property of the item and sub items.
Well the same item obviously cant exist in two different lists.
If the text is the same, then try looking by it:
foreach (ListViewItem listViewItem in l1.Items)
{
var item = l2.Items.Cast<ListViewItem>().Where(lvi => lvi.Text == listViewItem.Text);
item.Selected=true;
}
Or:
foreach (ListViewItem listViewItem in l2.Items.Cast<ListViewItem>()
.Where(lvi => l1.Items.Cast<ListViewItem>().Any(lvi2 => lvi.Text == lvi2.Text))
{
listVieItem.Selected=true;
}
IndexOf returns -1 if it cannot find the object passed to it in the list. My guess is that you have an issue with your equality comparison. Do the objects in the lists implement IComparable? Otherwise they may not be finding the items correctly and are reverting to a bad equality comparison. ListViewItem may not be comparing how you expect.
you can try finding the item by text and then get the index like this
foreach (ListViewItem item in firstListView.Items)
{
var itm = secondListView.FindItemWithText(item.Text);
int index = secondListView.Items.IndexOf(itm);
secondListView.Items[index].Selected = true;
secondListView.Select();
}
what FindItemWithText will do is get the item in secondListView which will be of same name as in firstListView and IndexOf will get the index of item in secondListView
Edit
This solution is good when you have two lists whose items are same and does not include any repetition in name else if you have two items in secondListView with same name FindItemWithText will get the first item only.

c# loop listbox selected items

I have a listbox on a form set to allow multiple selections. I want to loop through each selected item, store the selected value in a variable and do some work. I've tried many different variations of code to do this, but so far nothing has worked. Any help would be greatly appreciated! My code is below:
foreach (var item in systemList.Items)
{
string systemName = systemList.SelectedItems.ToString();
//do some work//
}
You can get all SelectedItems using below code:
var items = systemList.Items.Cast<ListItem>().Where(item => item.Selected);
You can then loop through the items
foreach (var item in items)
{
//Access value of each item by calling item.Value
}
foreach (var item in systemList.SelectedItems)
{
string systemName = item.ToString();
//do some work//
}
make sure listbox Selection mode is set to other than single!

C# - Remove items from List when button is clicked

My problem is; When click a button I input items in List, next in DropDownList. Problem is where i click button again exist items again into my DropDown.
How to solve this problem(sorry for image)?
List<string> companyList = new List<string>();
foreach (string item in companyList.ToList())
{
companyList.Remove(item); ----> this not working.......
}
foreach (SPListItem item in myItemCol)
{
companyList.Add(item["Company"].ToString());
}
companyList.Sort();
foreach (string item in companyList.Distinct())
{
ddComFilter.Items.Add(item.ToString());
}
You can use the Contains method to check if it is already there
if(!ddComFilter.Items.Contains(items.ToString())
{
ddComFilter.Items.Add(item.ToString());
}
This will only add the item if it is not already in the dropdown
You could check for existence of the item before add it to the list.
foreach (SPListItem item in myItemCol)
{
if(!companyList.Contains(item["Company"].ToString())
{
companyList.Add(item["Company"].ToString());
}
}
Then you need to clear the ddComFilter before adding the values to it:
companyList.Sort();
ddComFilter.Items.Clear();
foreach (string item in companyList.Distinct())
{
ddComFilter.Items.Add(item.ToString());
}
Alternate solution:
You can bind the ddComFilter using the generated list, instead for iterating the collection and add one-by-one. if so you need not to clear the collection, remove items etc. The code for this will be:
ddComFilter.Datasource = companyList;
ddComFilter.DataBind();
Here is an useful article for you
You should clear your dropdown before adding list as items:
companyList.Sort();
ddComFilter.Items.Clear(); // clear
foreach (string item in companyList.Distinct())
{
ddComFilter.Items.Add(item.ToString());
}

Categories