简体   繁体   English

如何使用窗体形式在C#中创建动态下拉列表

[英]how to create a dynamic drop down list in C# with window forms

I'm trying to build a simple inventory program for a friends cellphone store I want to use C# and access database to store the data 我正在尝试为朋友手机商店建立一个简单的库存程序,我想使用C#和访问数据库来存储数据

the DB will have 2 main lists: 数据库将有2个主要列表:

  1. devices - brand, model, color, price, stock,min_stock 设备 - 品牌,型号,颜色,价格,库存,min_stock
  2. parts - brand, model, description,stock,min_stock 零件 - 品牌,型号,描述,股票,min_stock

the GUI will use several drop lists brand will give me : samsung, htc, ect'.... model will give me : I9000,i9100,ect... GUI将使用几个下拉列表品牌将给我:三星,HTC,等...模型将给我:I9000,i9100等...

the two main problems I have when I try to think how to make it are this: 当我尝试思考如何制作它时,我遇到的两个主要问题是:

  • Each time new brands and models appear so i need an option to add a new model/brand to the database and then update the drop down list to have them automatically 每次出现新的品牌和型号时,我都需要选择将新的型号/品牌添加到数据库中,然后更新下拉列表以自动获取它们
  • The drop lists needs to be connected so if I choose brand A only brands A models will appear in the model drop list 需要连接下拉列表,因此如果我选择品牌A只有品牌A模型将出现在模型下拉列表中

First of all: don't use Access, use SQL Server 2008 Express. 首先:不使用Access,使用SQL Server 2008 Express。 But that's only personal taste. 但这只是个人品味。

What you need to do to achieve what you want: Create a typed dataset in Visual Studio that contains one table for brands and one for models. 您需要做什么才能实现您的目标:在Visual Studio中创建一个类型化数据集,其中包含一个品牌表和一个模型表。 Associate the two tables using a relation on the brand column. 使用brand列上的关系关联两个表。

Read both tables from the database - first the brands table, then the models table. 从数据库中读取两个表 - 首先是brands表,然后是models表。 Otherwise you'll get an error. 否则你会收到错误。

Create a master/detail binding for both lists. 为两个列表创建主/详细绑定。 To do so, drop two BindingSource instances to your form. 为此,请将两个BindingSource实例拖放到表单中。 Associate one of them to the "brands" list and one to the "devices" list. 将其中一个与“品牌”列表相关联,将一个与“设备”列表相关联。 The datasource for the "brands" BindingSource must be set to the brands table in the dataset, the datasource for the other BindingSource must be set to the relation between the two tables. 必须将“品牌” BindingSource的数据源设置为数据集中的brands表,其他BindingSource的数据源必须设置为两个表之间的关系 All of this can be one in the designer. 所有这些都可以是设计师中的一个。

If you have problems setting up the bindings, google for "C# master detail binding dataset". 如果您在设置绑定时遇到问题,请使用google查看“C#master detail binding dataset”。

EDIT 编辑
Another option - if the database connection is fast - would be to fill the list of brands from the database and whenever a brand is selected, clear and re-fill the list of models from the database on the fly using the selected brand name. 另一个选择 - 如果数据库连接速度很快 - 将填充数据库中的品牌列表,并且每当选择品牌时,使用所选品牌名称即时清除并重新填充数据库中的模型列表。

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

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