简体   繁体   English

将多个项目/对象添加到ListBox

[英]Add multiple items/objects to ListBox

I have 3 Dropdown Lists (could be more in future). 我有3个下拉列表(将来可能会更多)。

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. 我遇到的问题是DropdownList2和DropdownList3可能并不总是有一个子项,因此要将这些项添加到ListBox中,我可以存储它们的ID但显示其文本。

My database table has 3 columns to save the value (ID) from the 3 dropdown lists. 我的数据库表有3列,用于保存3个下拉列表中的值(ID)。

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? 我的问题是,如果我在ListBox中显示项目的文本,下一步是将数据保存到表中的相关列中(因此第1列将从DD1保存数据,第2列从DD2保存等)无论如何要确定该项目属于哪个ID,所以我可以将正确的ID保存到正确的列?

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. 因此,用户从DD1的DD1中选择了项目1,从DD2中选择了项目2,但DD3中没有可用的项目,因此他们单击添加将项目添加到列表框。 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? 当我必须保存该项目时,如何区分添加到DD2以上的项目,因此需要将其添加到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循环在列表中的对象上循环,并使用指针值来访问每个对象。

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. 让我知道您是否想进一步扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM