Add multiple items/objects to ListBox - c#

I have 3 Dropdown Lists (could be more in future).
DropdownList1 is a parent and is populated from a database.
DropdownList2 is a child and is populated from the selected item from DropdownList1.
DropdownList3 is a child and is populated from the selected item from DropdownList2.
I would like to add the selected item to a ListBox.
The problem i have is DropdownList2 and DropdownList3 may not always have a child item, so to add the items to a ListBox, i could store their IDs but display their text.
My database table has 3 columns to save the value (ID) from the 3 dropdown lists.
My question is if i display the text of the item in the ListBox, the next step is to save the data into the table into the relevant columns (so column 1 would save data from DD1, Column 2 would save from DD2 etc) is there anyway to identify which ID the item belongs to, so i can save the correct ID to the correct column?
So a user selects item 1 from DD1 item 2 from DD2, there is no item available from DD3, so they click add which adds the item to the ListBox. When i have to save this item how could i distinguish the item added was upto DD2 therefore it needs to be added to Column2? Or is there a better approach?
Hope this makes sense

List boxes don't like to store multiple values. They can, however, store objects as their datasource.
First create a custom object, then assign the values from each of your dropdown lists to the object:
Declare a new list of your custom object first
List<myObject> list = new List<myObject>();
then assign this to your button:
private void Button1_Click(object sender, EventArgs e)
{
myObject object = new myObject(Dropdown1, Dropdown2, Dropdown3);
list.Add(object);
//assign the list to the Listbox control
ListBox.Datasource = list;
}
When you want to access the values for your query, use a foreach loop to cycle over the objects in the list, with a pointer value to access each of them.
foreach (myObject obj in list)
{
var val1 = list[obj].Dropdown1;
var val2 = list[obj].Dropdown2;
var val3 = list[obj].Dropdown3;
//enter your sql code here
}
Let me know if you want to expand further.

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.

How to store list of items temporarily?

I am trying to store a list of items i.e. a value selected from dropdown and text from textbox temporarily and then adding them 1 by one to database using foreach loop on listbox.
code behind button add event:
ListBox ListBoxFeatures = new ListBox();
ListBoxFeatures.Items.Add(new ListItem(txtBoxDescription.Text, ddlFeatures.SelectedValue));
and then i have used a foreach loop over it to grab all stored values and store in database but it always pick 1 row, means that i store only 1 row.
foreach(ListItem li in ListBoxFeatures.Items)
{
String txt= li.Text;
Int Value= li.SelectedValue.ToInt32();
//database logic i.e. InsertMethod
}
Your problem is you create a new listbox in each click event. You need to move the initialization outside of the button click. Assuming that ListBoxFeatures already exists before the button click, you can probably remove the whole line of ListBox ListBoxFeatures = new ListBox(); from your click method.
Shouldn't it be:
foreach(ListItem li in ListBoxFeatures.Items)
{ ... }
UPDATE
Also, the button event always creates a new listbox and then inserts 1 value to it... Why would you have more than one value?

Adding data only to a specific Column

I'm trying to find a way to add data from one datagrid to another and for that data to be inserted to only one column at a time in my second datagrid. The specific column is created each time the Add button has been clicked.
My coding so far:
private void btnFeedbackAddSupplier_Click(object sender, RoutedEventArgs e)
{
dgFeedbackSelectSupplier.Items.Clear(); //So that my rows do not stack each other on every add
DataGridTextColumn columnSupplier = new DataGridTextColumn();
columnSupplier.Binding = new Binding("Supplier");
DataGridTextColumn columnFeedbackSupplierItem = new DataGridTextColumn();
//The 'Item' column is binded in XAML
columnSupplier.Header = (cmbFeedbackSelectSupplier.SelectedItem as DisplayItems).Name;
columnSupplier.IsReadOnly = true;
dgFeedbackAddCost.SelectAll(); //Selects all the rows in 1st datagrid
//Casts selected rows to my 'ViewQuoteItemList' class
IList list = dgFeedbackAddCost.SelectedItems as IList;
IEnumerable<ViewQuoteItemList> items = list.Cast<ViewQuoteItemList>();
var collection = (from i in items let a = new ViewQuoteItemList { Item = i.Item, Supplier = i.Cost }
select a).ToList();
//Adds both the column and data to the 2nd datagrid
dgFeedbackSelectSupplier.Columns.Add(columnSupplier);
foreach (var item in collection)
dgFeedbackSelectSupplier.Items.Add(item);
}
My reason for wanting to add the data to only one separate column at a time is because the data is different each time I want to add it to my 2nd datagrid and it overwrites any previous data that was entered in older add's.
EDIT: I Here are some images of what my current problem is
Here I add the first company and it's values. Everything works fine
Here I add the second company with it's new values, but it changes the values entered with the first company. This is my big problem. So you can see how my values are changed from the first to the second image
I think your problem here is that all your columns are bound to the same property: Supplier. Since you're updating that property everytime, all columns are assigned the same value. In the end, there's only one Supplier property for each row, so you can't show a different value for that single property on each column since everytime you change that property's value, the Bindings get notified and update themselves.
Maybe you could try using a OneTime Binding instead of a regular one. That way, the cells would retain the value they had when you first added them to the DataGrid. But for that to work, you should avoid clearing the DataGrid's items list, since re-adding the items would force them to rebind again.
Another option would be having a list of suppliers in your Supplier property, and have each column bind to an index of that list.
private void btnFeedbackAddSupplier_Click(object sender, RoutedEventArgs e)
{
// ...
columnSupplier.Binding = new Binding(string.Format("Supplier[{0}]", supplierColumnIndex));
// ...
var supplierCosts = new List<int>();
// ...
// Fill the list with the Costs of the Suppliers that correspond to each column and item
// ...
var collection = (from i in items let a = new ViewQuoteItemList { Item = i.Item, Supplier = supplierCosts }
select a).ToList();
//Adds both the column and data to the 2nd datagrid
dgFeedbackSelectSupplier.Columns.Add(columnSupplier);
foreach (var item in collection)
dgFeedbackSelectSupplier.Items.Add(item);
}

Getting multiple values from a List box in C# windows form

I have a list box that is pulling it's data from a sql table. I have its selection mode set to multisimple.
I have the display member for each item set to the Name field from the sql table and the value member for each item set to the ID field from the sql table.
When I select multiple items from the list, how do I get the multiple values? I am able to get the text of one item by using the listboxname.Text but I don't know how to get each value that has been selected all at once.
Any help will be greatly appreciated.
Use the SelectedItems property, the following will get a List<string> representing the selected items:
var items = listBox1.SelectedItems.Cast<object>()
.Select(x=>Convert.ToString(x)).ToList();
To get the exact values (ID), it depends on the underlying item type. If you use a DataTable as DataSource for your listBox, the underlying item type is DataRowView, so the code to get the values IDs should be:
var ids = listBox1.SelectedItems.Cast<DataRowView>()
.Select(row=>row.Row.Field<string>("ID")).ToList();
//suppose the ID field is string
If the underlying item type is just a normal class with 2 properties Name and ID, such as call it Item, the code is simpler like this:
var ids = listBox1.SelectedItems.Cast<Item>()
.Select(item=>item.ID).ToList();
Method 1 : You can use SelectedIndices property of the ListBox to get the All selected items Index values.
then for each selected index you can get the Value of the Item.
Try This:
private void button1_Click(object sender, EventArgs e)
{
List<String> SelectedItems=new List<String>();
foreach (int i in listBox1.SelectedIndices)
{
SelectedItems.Add(listBox1.Items[i].ToString());
}
}
Note : List SelectedItems contains all SelectedItems from the ListBox
Method 2:
You can use SelectedItems property of the ListBox to get the All selected item values directly.
Try This:
private void button1_Click(object sender, EventArgs e)
{
List<String> SelectedItems=new List<String>();
foreach (String s in listBox1.SelectedItems)
{
SelectedItems.Add(s);
}
}
Note : List SelectedItems contains all SelectedItems from the ListBox

how to select the main checkboxlist according to the sub checkboxlist in WinForm

I have a checkboxlist and it contains some items such as
100
100.001
100.002
100.003
200
200.001
200.002
200.003
these items have relationship between them. the parent items are 100 and 200.
100.001 , 100.002 and 100.003 are children of 100. and same for the items starts with 200
Lets say all items are UNSELECTED, for example, when user selects 100.002, I need to automatically select the parent which is 100.
what is a good way to that without looping?
here is my code
private void clb_SelectedIndexChanged(object sender, EventArgs e)
{
int selected = clb.SelectedIndex;
// I need to get the selected item's Text
// then I have to split it with
// string s = item.Text.Split('.')
clb.SetItemChecked(clb.FindStringExact(s[0]), true);
}
I am almost done with the above code, but I couldnt get the last selected item's text

Categories