Using Code if a condition is met to search for a similar product code, by trimstart, and then call a method to add that product to inventory list. Unfortunately it is causing a double addition so that the product is added twice.
If I use only the line of code for the List output to a GridView it displays one entry normally.
if (item.Name.StartsWith("D"))
{
string name = item.Name.TrimStart('D');
List<Item> dvd = items.SelectByName(name);
foreach (Item item2 in dvd)
{
Class.AddItem(item2.Id, item2.Id2, item2.Name);
}
}
Can you check in your foreach, right before you AddItem, if the item already exisits in that class? If no, add, if yes, continue.
Here is some pseudo that you could try to add some validation before adding the item to the list:
if !the_list.Contains(the_name)
the_list.Add(item)
Related
There's a checklist that contains strings .
There is a for each loop that checks the checked items and then add those items to the list of strings that's called mylist only if they aren't added already.
What i need is to check for the not checked items in the listbox and remove the strings from mylist after unchecking item from box .
Basicaly i have a list called mylist i need to add whatever checked item from checkedboxlist to mylist and whenever i uncheck an item delete the same string from mylist .
Suggest some solutions. Thanks in advance .
Please, be so kind and review your next question (How to Ask)...
Take advantage of the event anyCheckedListBox.ItemCheck (MSDN):
public class Form1 : Form {
ListBox anyListBox;
CheckedListBox anyCheckedListBox;
public Form1() {
anyListBox = new ListBox();
Controls.Add(anyListBox);
anyCheckedListBox = new CheckedListBox();
anyCheckedListBox.Items.Add("test1");
anyCheckedListBox.Items.Add("test2");
anyCheckedListBox.Items.Add("test3");
anyCheckedListBox.ItemCheck += AnyCheckedListBox_ItemCheck;
Controls.Add(anyCheckedListBox);
}
private void AnyCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.CurrentValue == CheckState.Unchecked)
anyListBox.Items.Add(anyCheckedListBox.Items[e.Index]);
else
anyListBox.Items.Remove(anyCheckedListBox.Items[e.Index]);
}
}
Beware that the strings have to be unique with this quick and dirty solution.
The naïve implementation would be to add a call to List.Remove in your loop if the item is not checked. Assuming the code you have is similar to #AustinFrench's comment, something like:
foreach (var box in checkboxList)
{
if (box.IsChecked && !myList.Contains(box.Text))
{
// if it's checked, add it to the list if it's not already there
myList.Add(box.Text);
}
else if (!box.IsChecked)
{
// if it's not checked, try to remove it from the list
myList.Remove(box.Text);
}
}
Note that you do not need to check whether an item exists before calling List.Remove. It will simply return false if the item does not exist.
Additionally note this is an O(n^2) operation. It is potentially checking the entire contents of myList for each item in your checkboxlist. If the lists are long, you may get better performance by sorting the lists first and making a single simultaneous pass through the pair (or at least sort myList so you can search it more efficiently).
Alternatively, consider completely replacing the contents of myList instead. This requires only a single pass through your checkboxlist:
myList.Clear();
foreach (var box in checkboxList)
{
if (box.IsChecked)
myList.Add(box.Text);
}
Or, using LINQ and taking advantage of List.AddRange:
myList.Clear();
myList.AddRange(checkboxList.Where(box => box.IsChecked).Select(box => box.Text));
The below code has a foreach loop that iterates through a list of CheckBoxes and then checks if each item is checked or not. If not checked then gets the index of that entry from myList and uses RemoveAt method to remove that entry from the list using the index.
foreach (var item in checkboxList)
{
if (!item.IsChecked)
{
int index = myList.IndexOf(item);
if(index != -1)
myList.RemoveAt(index);
}
}
C# How to prevent ListBox in MultiSimple selection mode to select first item automatically, when you unselect the last one selected item in the box - it happens only if listbox represented by my own class objects, and everything is ok when it represented by string objects. Thnx!
It seems like keeping track of the order of the list is the most important part. I would suggest maybe making an array of a struct. You can make this struct contain whatever you want for example:
struct itemList
{
public string itemName;
public int itemIndex;
//include whatever other variables that you need included in here.
}
Also, make sure you place your struct before the namespace. Then, making the array of the struct would look like this:
itemList[] items1 = new itemList[listBoxName.SelectedItems.Count];
All you would have to do then is to add the items to the array before you reorder the listBox
for (int i = 0; i < listBoxName.SelectedItems.Count; i++)
{
items1[i].itemName = listBoxName.SelectedItems[i].ToString();
items1[i].itemIndex = listBoxName.SelectedIndices[i];
}
Thank you very much, but i already use some like this. I don't understand why first item of listBox selected everytime i assign preloaded list as DataSource. I resolve this problem, by making another one temporal List of my object class, which items readed from binary file, and then push them one by one to my original List in foreach cycle by listOfObjects.Add(object) method. I know that every time after code ListOfTags.DataSource = null;
ListOfTags.DataSource = tags;
ListOfTags.DisplayMember = "Name"; if my tags (it is a List) are preloaded even in code (for example if i write code List<Tag> tags = new List<Tag> {new Tag("1"),new Tag("2"), new Tag("3")}; , this takes situation when first item of listbox selected, and starts selects everytime after that when i try do deselect last selected item in listBox.
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 am having a difficulty adding an item to my listbox. I want to add an item at the beginning of the list box to be my 'default' item, however I will also be adding a list of items from a List using the .DataSource ... and for some reason the app is crashing whenever I try to add the items from the List and the default item at the same time. I am trying to add the items by using:
`productList.DataSource = salesManager.Products;
productList.DisplayMember = "IdAndName";
productList.ValueMember = "Id";
productList.Items.Insert(0, "ALL");`
but for some reason VS will not let me. I have also found this method and tried to apply it as well:
public void AddListLine(string lineIn)
{
productList.Items.Insert(0, "ALL");
((CurrencyManager)productList.BindingContext[productList]).Refresh();
}
However it is not working as well. Any idea please? Thanks!
The reason it isn't working is because you are attempting to add an object of type String where the rest are (I assume) of type Product or something similar. The runtime attemps to access the property IdAndName to display and the property Id for the display and value properties of the new list item and they do not exist.
Consider adding some kind of "blank" Product object instead.
public void AddListLine(string lineIn)
{
productList.Items.Insert(0, new Product { Id = "ALL", IdAndName = "ALL" });
((CurrencyManager)productList.BindingContext[productList]).Refresh();
}
I've created some drop down lists using JavaScript, ASP.NET.
A user can add as many drop down lists as he wants by clicking a "+" button and removing them by clicking a "-" button.
If it's hard to understand what I mean pls see " How to implement a list of dropboxes in C# ".
And now I'd like to implement the code behind and want to define the order of the drop down lists, but I don't know which one is my first drop down list, etc.
We assume that all <asp:DropDownList> contain the following for list elements: method1, method2, method3 and method4. If a user selects an element, a method in the codebehind is implemented.
Example:
dropboxlist1: select list item method2,
dropboxlist2: select list item method1,
dropboxlist3: select list item method3,
string txt= "";
if (dropboxlistID.Text == "method1"){
txt = method1Imp();
} else if (dropboxlistID.Text == "method2") {
txt = method2Imp();
} else if (dropboxlistID.Text == "method3") {
txt = method3Imp();
} else {
}
But at this moment I don't have any idea which drop down lists came first and which method should be performed on my string first.
Try enqueueing each method into a queue as a delegate, then draining (invoking each delegate) the queue once you're ready from a single thread. This will ensure that the order of execution matches the order of user choices.
Sorry I didn't initally include code. Here's a basic example to get you started:
Queue<Func<string>> actions = new Queue<Func<string>>();
if(dropboxListID.Text =="m1")
{
actions.Enqueue(method1Imp);
}
if(dropboxListID.Text = "m2")
{
action.Enqueue(method2Imp);
}
...
Sometime Later when you're ready to process these
...
string txt = "";
while(actions.Count >0)
{
var method = actions.Dequeue();
txt = method();
}
Here's a blog post that delves further into the concept of a work/task queue:
http://yacsharpblog.blogspot.com/2008/09/simple-task-queue.html
IMO your drop down lists will be contained in a parent.
Let us say (acc to your link) your parent is DropDownPlaceholder.
<div id="DropDownPlaceholder">
Use linq to get all children of it. Cast them as drop down lists and then your can loop on them to find your matter.
To get the order of dropdownlists:
First set the IDs/ClientIDs of hard-coded dropdownlists in aspx page and
count them (say 2 dropdownlists are present)
While creating dropdownlists dynamically, append a count integer at
the end of their IDs/ClientIDs like ddl3, ddl4 (start the count from 3)
Then in your code, you can find the dropdownlist of selected element:
if (ddl.ClientID.EndsWith("1")){
// 1st ddl
} else if (ddl.ClientID.EndsWith("2")) {
// 2nd ddl
} else if (ddl.ClientID.EndsWith("3")) {
// 3rd ddl
}
...