remove item in dictionary using value - c#

i have a dictionary that you can add cards to by searching on a listbox but now i want to be able to remove that item from the dictionary if the user presses a button here is the code i use to add a value to the dictionary
if (!m_banlists[BanList.Items[BanList.SelectedIndex].ToString()].Exists(banListCard => banListCard.ID == Program.CardData[cardid].Id))
{ m_banlists[BanList.Items[BanList.SelectedIndex].ToString()].Add(
new BanListCard { ID = Program.CardData[cardid].Id, Banvalue = 0, Name = Program.CardData[cardid].Name });
}
i wont post all the code as its too long
heres the code i use to remove an item
var list = (ListBox) sender;
if (list.SelectedIndex != -1)
{
int cardid = Int32.Parse((string)list.SelectedItem.ToString());
if (m_banlists[BanList.Items[BanList.SelectedIndex].ToString()].Exists(banListCard => banListCard.ID == Program.CardData[cardid].Id))
{
m_banlists[BanList.Items[BanList.SelectedIndex].ToString()].Remove();
list.Items.RemoveAt(list.SelectedIndex);
}
}
but i cant figure out what to put in the brackets of remove to find the value oh and it needs to look for the ID value

I think you can try this
m_banlists[BanList.Items[BanList.SelectedIndex].ToString()].ToList().RemoveAll(x=>x.ID==someId);

Related

Check if list view contain item

i have a listview with 3 columns (id , name, author), i use this method to add row:
public void addToLv(Book book)
{
//TODO: Verifier si l'item existe avant d'ajouter
ListViewItem lvi1 = new ListViewItem(book.id.ToString());
lvi1.Text = book.id.ToString();
lvi1.SubItems.Add(book.name);
lvi1.SubItems.Add(carte.author);
listView1.Items.Add(lvi1);
}
Now i wan't to check if book exists before i insert the new one to avoid duplicate element, i try this code but it'S not working
i have use this line but it's not working:
(listView1.Items.ContainsKey(book.id))
{
listView1.Items.Add(lvi1);
}
Can you help me please? thank you
From MSDN:
The key comparison is not case-sensitive. The Name property corresponds to the key for a ListViewItem in the ListView.ListViewItemCollection.
So, you have to set the Name in order to use ContainsKey
lvi1.Name = book.id.ToString();
And then the rest like you did:
if (!listView1.Items.ContainsKey(book.id.ToString()))
{
listView1.Items.Add(lvi1);
}
I think you missed a "!" (not) in your code.
(!listView1.Items.ContainsKey(book.id))
{
listView1.Items.Add(lvi1);
}
Your code is saying that if your listview contains that key, you will add another entry that has that key. But it seems you want to do the opposite, right? If your listview does not contain an entry with that key, you want to add an entry that has that key.
It looks like you are storing your individual names on the SubItems property, so you'll need to query that to see if a given book name is present. You can do this using a bit of LINQ as follows:
// If your ListView doesn't contain any items that have a given book as a SubItem
// then add one
if (!listView1.Items.Any(i => i.SubItems.ContainsKey(book.Name))
{
listView1.Items.Add(lvi1);
}
Since your edit indicates that you actually want to check for the ID instead, which is stored at the ListItem-level, then you would just need to slightly adjust your condition to check the Text property since the ListViewItem(string) constructor sets the Text property by default:
if (!listView1.Items.Any(i => i.Text == book.id))
{
listView1.Items.Add(lvi1);
}
If any thing works, try this:
public void addToLv(Book book)
{
//TODO: Verifier si l'item existe avant d'ajouter
ListViewItem lvi1 = new ListViewItem(book.id.ToString());
//lvi1.Text = book.id.ToString();
lvi1.SubItems.Add(book.name);
lvi1.SubItems.Add(carte.author);
if (!existChecker(book.id.ToString()))
listView1.Items.Add(lvi1);
}
private bool existChecker(string id)
{
bool exist = false;
for (int i = 0; i < lvi1.Items.Count && exist != true; i++)
{
if (lvi1.Items[i].SubItems[0].Text == id)
exist = true;
}
return exist;
}
LINQ can't be used for this:
if (!listView1.Items.Any(i => i.SubItems.ContainsKey(book.Name))
The only real way of doing it is to use the search functionality as thus:
if (listView1.FindItemWithText(book.Name) != null)
{
// Do the business...
}
etc...

c# How to prevent duplicate listview by column text

I need to prevent Duplicate entries from ListView controller by column text. if duplicate found I need to get the ListView Item for further process. I saw every one says
ListViewItem item = ListView3.FindItemWithText("test");
if (!listView1.Items.ContainsKey(txt))
{
// doesn't exist, add it
}
but how can I point which Column text?? I did prevent duplicates by adding ids into a array and after check array value exists. but in that case I can find which entry duplicated.
this is my code.
rd = cmd.ExecuteReader();
// Validation not working - duplicating ListviewItems
while (rd.Read()) {
ListViewItem lvvi = new ListViewItem(rd.GetString(0));
lvvi.SubItems.Add(rd.GetString(1));
lvvi.SubItems.Add(rd.GetString(5));
lvvi.SubItems.Add("1");
lvvi.SubItems.Add(rd.GetString(0));
int listViewItemID;
int[] ids;
ids = new int[100];
if (listView3.Items.Count > 0)
{
int addingItemID;
//ADD ListView ids into array
int i=0;
foreach (ListViewItem li in listView3.Items)
{
listViewItemID = Int32.Parse(li.SubItems[0].Text);
addingItemID = Int32.Parse(rd.GetString(0));
ids[i] = listViewItemID;
i++;
}
//Check item allready exsist
if (ids.Contains(Int32.Parse(rd.GetString(0))))
{
MessageBox.Show("sdsd");
}
else {
listView3.Items.Add(lvvi);
}
}
else {
listView3.Items.Add(lvvi);
}
}
//Calculate Price summery
this.calculatePrice();
Instead of looping to get all id's, you can loop through the items or use linq to find the specific id and keep the result. This can be done in an external function or by replacing the ids portion with the loop or use something like FirstOrDefault:
addingItemID = rd.GetString(0);
ListViewItem existing = listView3.Items.Cast<ListViewItem>().FirstOrDefault(li => li.SubItems[0].Text == addingItemID); //(not sure if the cast is needed)
if (existing != null)
{
//item exists, variable existing refers to the item
MessageBox.Show("sdsd");
}
else
{
listView3.Items.Add(lvvi);
}

Can not find index of combobox item when using a List as datasource

I'm populating a list from a LINQ Query, then I am using the list as the data source for a combo box.
I am then trying to select items within the combo box but it doesn't seem to be able to find the index
using (var db = new CruxEntities())
{
var query = from q in db.Businesses
where q.BusinessID == BusinessId
select q;
var B = query.FirstOrDefault();
if (B != null)
{
// other form controls populated
var sites = B.TblBusinessSites.ToList();
this.comboBox.DisplayMember = "SiteName";
this.comboBox.ValueMember = "BusinessSiteID";
this.comboBox.DataSource = sites;
int index = comboBox.FindString(B.IdFromLinq);
}
}
index always has the value of -1 assigned to it but i've stepped through the code and I know that the value exists in the list... it seems to be that the rest of the code is not recognising that the combo box has the values.
What am I missing?
Edit
I got the index fine... but something I missed out from my initial post is that there are 2 combo boxes bound to the list... I get the indexes for both of them fine when I step through the code but the combo boxes seem linked so I assigning the index to either one seems to assign it to both...
index = sites.FindIndex(s => s.BusinessSiteID == B.PrimarySiteDeliveryID);
comboBox_DefaultDeliverySite.SelectedIndex = index;
index = sites.FindIndex(s => s.BusinessSiteID == B.PrimarySiteInvoiceID);
comboBox_DefaultInvoiceSite.SelectedIndex = index;
You can't find site index because FindString method checks item's displayed text (site name in your case), but you are trying to search by ID, which is item's value.
Actually you even don't need to touch combobox here, because items will be added in same order as you have them in sites collection. To get index of some site you can just search index of site in sites list:
int index = sites.FindIndex(s => s.BusinessSiteID == B.IdFromLinq);
The FindString method is not a good choice, since you are binding with objects, so stick to object, not string.
You can loop on your item instead :
foreach(var item in comboBox.Items)
{
var businessSite = item as BusinessSite;
if(businessSite != null && businessSite.BusinessSiteID == B.IdFromLinq)
{
// your item here
}
}
Or index based:
for(int index = 0; index < comboBox.Items.Count; index++)
{
var item = comboBox.Items[index];
var businessSite = item as BusinessSite;
if(businessSite != null && businessSite.BusinessSiteID == B.IdFromLinq)
{
return index;
}
}

How to set Selected item of ComboBox in C# Windows Forms?

I am trying to set selected item of comboBox on click event of DataGrid, but I could not. I have googled and tried different ways but without success.
For me SelectedIndex is working, but I could not find the index of items in ComboBox, so I could not select the item.
Not working code:
for (int i = 0; i < cmbVendor.Items.Count; i++)
if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
{
cmbVendor.SelectedIndex = i;
break;
}
You can get your item index by the .Items.IndexOf() method. Try this:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf(gridView1.GetFocusedRowCellValue("vVendor"));
You don't need to iterate.
You can find more information in Stack Overflow question How do I set the selected item in a comboBox to match my string using C#?.
The following is working for me perfectly. Pass any value or Text which is available in the combobox.
comboBox1.SelectedIndex = comboBox1.FindString(<combobox value OR Text in string formate>);
You have it in your if:
cmbVendor.SelectedItem = cmbVendor.Items[i];
At last I found it out. It's:
cmbVendor.Text = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.
If you have set ValueMember property for the ComboBox control, you can simply assingn the Value to the ComboBox control's SelectedValue property. You don't have to find the index explicitly.
Here's an example:
public class Vendor{
public int VendorId {get; set;}
public string VendorName {get; set;}
}
// Inside your function
var comboboxData = new List<Vendor>(){
new Vendor(){ vendorId = 1, vendorName = "Vendor1" },
new Vendor(){ vendorId = 2, vendorName = "Vendor2" }
}
cmbVendor.DataSource = comboboxData;
cmbVendor.DisplayMember = "VendorName";
cmbVendor.ValueMember = "ValueId";
// Now, to change your selected index to the ComboBox item with ValueId of 2, you can simply do:
cmbVendor.SelectedValue = 2;
Assuming gridView1.GetFocusedRowCellValue("vVendor") really works as expected, the following code should fix the problem.
string selected = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
foreach ( var item in cmbVendor.Items )
{
if (string.Compare(item.ToString(), selected, StringComparison.OrdinalIgnoreCase) == 0)
{
cmbVendor.SelectedItem = item;
break;
}
}
The original code had multiple calls to gridView1.GetFocusedRowCellValue("vVendor"), whereas you only need one.
The suggested "comboBox1.Items.IndexOf(" assumes too much about the content of cmbVendor.Items.
I had a similar problem and worked it out partially with the help of the other answers here. First, my particular problem was that
combobox1.SelectedItem = myItem;
was not working as expected. The root cause was that myItem was an object from a group which was effectively the same list as the items in the combobox, but it was actually a copy of those items. So myItem was identical to a valid entry, but itself was not a valid object from the combobox1 container.
The solution was to use SelectedIndex instead of SelectedItem, like this:
combobox1.SelectedIndex = get_combobox_index(myItem);
where
private int get_combobox_index(ItemClass myItem)
{
int i = 0;
var lst = combobox1.Items.Cast<ItemClass >();
foreach (var s in lst)
{
if (s.Id == myItem.Id)
return i;
i++;
}
return 0;
}
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String From DataGrid Cell value")
Try this this will work fine in C# Windows application
this works for me.....
string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;

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