ListView CheckedItems find item by name - c#

I need to check if an item with a particular name exists in the CheckedItems collection of a ListView.
So far I've tried:
ListViewItem item = new ListViewItem(itemName);
if (listView1.CheckedItems.IndexOf(item) >= 0)
return true;
and
ListViewItem item = new ListViewItem(itemName);
if (listView1.CheckedItems.Contains(item))
return true;
Neither of those worked. Is there a way to do this without looping through CheckedItems and checking them one by one?

You can benefit LINQ for this purpose:
bool itemChecked = listView1.CheckedItems.OfType<ListViewItem>()
.Any(i => i.Text == itemText);
//You can also retrieve the item with itemText using FirstOrDefault()
var checkedItem = listView1.CheckedItems.OfType<ListViewItem>()
.FirstOrDefault(i=>i.Text == itemText);
if(checkedItem != null) { //do you work...}
You can also use the ContainsKey to determine if the item (with name being itemName) is checked:
bool itemChecked = listView1.CheckedItems.ContainsKey(itemName);

Get rid of newing up a ListViewItem and do this instead:
ListViewItem itemYouAreLookingFor = listView1.FindItemWithText("NameToLookFor");
// Did we find a match?
if (itemYouAreLookingFor != null)
{
// Yes, so find out if the item is checked or not?
if(itemYouAreLookingFor.Checked)
{
// Yes, it is found and check so do something with item here
}
}

Using new, you are creating a new item which is not added to the list view (since it is new) and can therefore not be found when using listView1.Contains(item).
When you add an item, use a key/value pair and use contains on the values.

Related

Is it possible to find a particular value from Dropdown datasourse in c#?

I need to check, particular value whether available in the loaded dropdown list data source, How to do it?
Here is the code which I tried and it works fine, but is there any simple way to find it?
if (ddlcountry.Items.Contains(ddlcountry.Items.FindByValue(drJob["Country"].ToString())) == true)
{
ddlcountry.SelectedValue = drJob["Country"].ToString(); //if available it assigns the value
}
Following is much simpler:
ListItem item = ddlcountry.Items.FindByValue(drJob["Country"].ToString());
if(item != null)
ddlcountry.SelectedValue = item.Value;

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.

How do I find out if individual items in CheckedListBox are checked? C#

I've tried looking in checkedListBox1.Items, but that didn't help. So how do I check if an item in a CheckedListBox is marked? It's in a windows forms application.
You can get a list of checked items using CheckedItems property.
Example 1:
foreach (var item in this.checkedListBox1.CheckedItems)
{
MessageBox.Show(item.ToString());
}
Example 2:
this.checkedListBox1.CheckedItems.Cast<object>()
.ToList()
.ForEach(item =>
{
//do stuff here
//for example
MessageBox.Show(item.ToString());
});
If you are sure items are string for example, you can use Cast<object> in above code.
You can get the list of checked indices using CheckedIndices property.
Example:
this.checkedListBox1.CheckedIndices.Cast<int>()
.ToList()
.ForEach(index =>
{
//do stuff here
//for example
MessageBox.Show(this.checkedListBox1.Items[index].ToString());
});
try this:
foreach (ListItem item in checkedListBox1.Items)
{
if (item.Selected)
{
// If the item is selected
}
else
{
// Item is not selected, do something else.
}
}

c# Is there a option to filter a listbox

I want to know if there is a possibility to filter a listbox. I mean it in such a way that is i add an item and the name is already in the listbox that you get a messagebox.show that tells you"Item already in the listbox". And that it won't be added twice.
You don't need to iterate throug the items as the Items collection of the ListBox implements the "Contains" method.
if (listBox1.Items.Contains(Item))
{
MessageBox.Show("ListBox already contains Item");
}
"Item" is in this case the Item from the other ListBox
Update. You could write:
if (listBox1.Items.Contains(listBox2.SelectedItem))
{
MessageBox.Show("ListBox already contains Item");
}
else
{
listBox1.Items.Add(listBox2.SelectedItem);
}
Use data binding might be one of the solutions:
List<string> SomeData=...
var filtered=SomeData.Where(...); // <-- Your filtering condition here
listBox1.DataSource = new BindingSource(choices, null);
Inside the event/method which adds list items inside your listbox you can add something like:
// search for list item in the listbox which has the text
ListItem li = theListBox.Items.FindByText("yourListItemName");
if (li != null)
{
// if list item exists display message
MessageBox.Show("ListBox already contains item with the name");
}
else
{
theListBox.Items.Add("yourListItemName");
}
here is a sample code try and implement it in you code
ListBox.ObjectCollection ListItem1= ListBox1.Items;
if(!string.IsNullOrEmpty(SearchBox.Text))
{
foreach (string str in ListItem1)
{
if (str.Contains(SearchBox.Text))
{
msgbox;
}
}
}

Prevent double entries in ListView using C#?

How can we access the items added to a ListView?
The thing I have to do is: add an item to the list view. I want to check if the item to add to the listview is already present in the ListView.
I'm using C# and Visual Studio 2005.
The ListView class provides a few different methods to determine if an item exists:
Using Contains on the Items collection
Using one of the FindItemWithText methods
They can be used in the following manner:
// assuming you had a pre-existing item
ListViewItem item = ListView1.FindItemWithText("test");
if (!ListView1.Items.Contains(item))
{
// doesn't exist, add it
}
// or you could find it by the item's text value
ListViewItem item = ListView1.FindItemWithText("test");
if (item != null)
{
// it exists
}
else
{
// doesn't exist
}
// you can also use the overloaded method to match sub items
ListViewItem item = ListView1.FindItemWithText("world", true, 0);
Just add your items and make sure you assign a name. Then
just use the ContainsKey method of the Items collection to
determine if it's there, like this.
for (int i = 0; i < 20; i++)
{
ListViewItem item = new ListViewItem("Item" + i.ToString("00"));
item.Name = "Item"+ i.ToString("00");
listView1.Items.Add(item);
}
MessageBox.Show(listView1.Items.ContainsKey("Item00").ToString()); // True
MessageBox.Show(listView1.Items.ContainsKey("Item20").ToString()); // False
You could do something like this:
ListViewItem itemToAdd;
bool exists = false;
foreach (ListViewItem item in yourListView.Items)
{
if(item == itemToAdd)
exists=true;
}
if(!exists)
yourListView.Items.Add(itemToAdd);
The following will help to locate a ListViewItem within the ListView control once you've added it:
string key = <some generated value that defines the key per item>;
if (!theListViewControl.Items.ContainsKey(key))
{
item = theListViewControl.Items.Add(key, "initial text", -1);
}
// now we get the list item based on the key, since we already
// added it if it does not exist
item = theListViewControl.Items[key];
...
Note
The key used to add the item to the ListView items collection can be any unique value that can identify the ListViewItem within the collection of items. For example, it could be a hashcode value or some property on an object attached to the ListViewItem.
A small correction in Robban's answer
ListViewItem itemToAdd;
bool exists = false;
foreach (ListViewItem item in yourListView.Items)
{
if(item == itemToAdd)
{
exists=true;
break; // Break the loop if the item found.
}
}
if(!exists)
{
yourListView.Items.Add(itemToAdd);
}
else
{
MessageBox.Show("This item already exists");
}
In case of multicolumn ListView, you can use following code to prevent duplicate entry according to any column:
Let us suppose there is a class Judge like this
public class Judge
{
public string judgename;
public bool judgement;
public string sequence;
public bool author;
public int id;
}
And i want to add unique object of this class in a ListView. In this class id is unique field, so I can check unique record in ListView with the help of this field.
Judge judge = new Judge
{
judgename = comboName.Text,
judgement = checkjudgement.Checked,
sequence = txtsequence.Text,
author = checkauthor.Checked,
id = Convert.ToInt32(comboName.SelectedValue)
};
ListViewItem lvi = new ListViewItem(judge.judgename);
lvi.SubItems.Add(judge.judgement ? "Yes" : "No");
lvi.SubItems.Add(string.IsNullOrEmpty(judge.sequence) ? "" : txtsequence.Text);
lvi.SubItems.Add(judge.author ? "Yes" : "No");
lvi.SubItems.Add((judge.id).ToString());
if (listView1.Items.Count != 0)
{
ListViewItem item = listView1.FindItemWithText(comboName.SelectedValue.ToString(), true, 0);
if (item != null)
{
// it exists
}
else
{
// doesn't exist
}
}

Categories