adding an additional item to a listbox - c#

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

Related

Why DbContext Save Only One from List of Item?

I am using AspNetNet 6.
In my Page I have two [BindProperty]:
tblUserToRoute Class (Entity Class)
int[] SelectedRouteIds (Get Selected Item By User)
When client select several item in ListBox and click on save button, in my "OnPost" method I receive correct model and an array of selected value from ListBox which stored in "SelectedRouteIds" property. Everything is ok so far.
For save model for each selected item in ListBox I used "foreach" like below:
foreach (int item in SelectedRouteIds)
{
tblUserToRoute.fldRouteId = item; //set selected item
db.tblUserToRoute.Add(tblUserToRoute); //add model to repository
}
db.SaveChanges();
What I have done is: in each loop I set field value to selected item value from ListBox and then add model to context and after "foreach" loop I tried to save changes but, only one model saved to database and other model which have been passed to context not saved.
Why context cannot save multi added model? for this scenario how can I proceed?
thank you all
I changed my codes inside "foreach" like below:
db.tblUserToRoute.Add(new cesEntities.Models.cesUser.tblUserToRoute()
{
fldUserId = user.fldId,
//set item (only value which should be changed in each loop)
fldRouteId = item,
fldDateExpiry = tblUserToRoute.fldDateExpiry,
fldPermanent = tblUserToRoute.fldPermanent,
fldValid = tblUserToRoute.fldValid,
fldDefault = tblUserToRoute.fldDefault,
});
Now SaveChanges() method works correctly.
Thank you all.

C# How to prevent ListBox to select first item when you unselect the last one

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.

Using C# to auto add item, double entries for unknown reason

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)

Bind ComboBox to Two Lists in C#

I have two lists. The first one is hard-coded and the contents never change. The second can be edited by the user to add, change and remove items:
public List<Item> DefaultItems = new List<Item>();
public BindingList<Item> UserItems = new BindingList<Item>();
...
MyTable.DataSource = UserItems;
I would like to bind the contents of both lists, one after the other, to a ComboBox and have it update automatically when the user edits the UserItems list.
The first part I can easily solve with something like:
public List<Items> AllItems
{
get
{
List<Item> Items = new List<Item>();
foreach (Item I in DefaultItems) Items.Add(I);
foreach (Item I in UserItems) Items.Add(I);
return Items;
}
}
...
MyComboBox.DataSource = AllItems;
The problem is that when UserItems changes there is no notification that AllItems has changed so the contents of the combobox remain the same.
I then added an event that is generated when UserItems changes. Now my problem is how to force the ComboBox to refresh. Doing the following:
MyComboBox.DataSource = null;
MyComboBox.DataSource = AllItems;
results in the selecteditem becoming null and the selectedindex becoming -1, which I then have to handle in my code (temporarily remember the current item, restore it afterwards, etc.). It's all becoming very messy and I'm sure there is a clever way of solving this. Is there?
thanks, Andy
UPDATE: I didn't want to add yet more code and complexity just for this in the form of a third party assembly, so I just continued with my messy approach. Thanks.
You need to use a collection that will notify the UI when the collection has been changed.
You can either use the .NET provided BindingList class or, if you want to try something different, you could download the BindingListView class that will wrap your existing collections and provide the UI with the notification it needs.

Setting default item in combo box

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

Categories