WinForms上的多项选择
时间:2020-03-05 18:40:23 来源:igfitidea点击:
在Windows窗体中实现多选选项的最佳方法是什么?我想从默认值开始,从列表中强制执行一个选择。
似乎ComboBox是一个不错的选择,但是有没有办法指定一个非空白的默认值呢?
我可以在适当的初始化点在代码中进行设置,但感觉好像丢失了一些东西。
解决方案
回答
我们应该能够只将ComboBox.SelectedIndex属性设置为我们想要的默认值。
http://msdn.microsoft.com/zh-CN/library/system.windows.forms.combobox.selectedindex.aspx
回答
插入项目后,使用ComboBox.SelectedItem或者SelectedIndex属性选择默认项目。
我们还可以考虑使用RadioButton控件来强制选择单个选项。
回答
如果我们只希望从小组中得到一个答案,那么RadioButton控件将是最佳选择,或者,如果我们有很多选择,可以使用ComboBox。要设置默认值,只需将项目添加到ComboBox的集合中,然后将SelectedIndex或者SelectedItem设置为该项目。
根据要查看的选项的数量,可以将ListBox的SelectionMode属性设置为MultiSimple(如果这是多个选择),或者可以使用CheckBox控件。
回答
我们可以将ComboBox与DropDownStyle属性设置为DropDownList并将SelectedIndex设置为0(或者任何默认项)一起使用。这将强制始终从列表中选择一个项目。如果我们忘记这样做,则用户可以在编辑框部分输入其他内容,这很不好:)
回答
如果我们要为用户提供一小部分选择,请坚持使用单选按钮。但是,如果我们想将组合框用于动态列表或者长列表。将样式设置为DropDownList。
private sub populateList( items as List(of UserChoices)) dim choices as UserChoices dim defaultChoice as UserChoices for each choice in items cboList.items.add(choice) '-- you could do user specific check or base it on some other '---- setting to find the default choice here if choice.state = _user.State or choice.state = _settings.defaultState then defaultChoice = choice end if next '-- you chould select the first one if cboList.items.count > 0 then cboList.SelectedItem = cboList.item(0) end if '-- continuation of hte default choice cboList.SelectedItem = defaultChoice end sub