gpt4 book ai didi

c# - WinForms/C# : Adding items to Combox and controlling the Item value (numeric)

转载 作者:太空宇宙 更新时间:2023-11-03 20:36:57 26 4
gpt4 key购买 nike

我一直在使用设计器将我的项目填充到组合框中,我传递的只是一个字符串。

虽然现在我需要控制每个项目存储哪个键/索引。

我以为有一个项目对象,但我查看了 ADD 方法,它接受对象..

我如何在控件中传递键/索引,即当我执行 SelectedItem 时返回的内容。

因此,如果我执行 selectedtext,我会取回一个显示在当前选定下拉列表中的字符串,但如果我执行 selecteditem,我想取回一个我需要与之一起存储的自定义编号...

有什么办法吗?

提前致谢

最佳答案

您需要将其绑定(bind)到一组键\值对象并使用 DisplayMemberValueMember属性来设置显示/返回的内容。

举个例子:

public class ComboItem
{
public string stringValue { get; set; }
public int indexValue { get; set; }
}

public void LoadCombo()
{
List<ComboItem> list = new List<ComboItem>();
// populate list...
// then bind list
myComboBox.DisplayMember = "stringValue";
myComboBox.ValueMember = "indexValue";
myComboBox.DataSource = list;
}

然后

myComboBox.SelectedText       // will return stringValue
myComboBox.SelectedValue // will return indexValue
myComboBox.SelectedItem // will return the ComboItem itself
myComboBox.SelectedIndex // will return the items index in the list

或者,您可以通过添加 Tag 来存储索引通过创建自定义组合项 have a read here for how to do this 属性(通常用于存储此类内容)

关于c# - WinForms/C# : Adding items to Combox and controlling the Item value (numeric),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4691731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com