我的建议是构建一个包含您需要的所有值的类,然后使用List<class> 设置ComboBox.DataSource 属性。
将 DisplayMember 设置为要用作列表可见字符串的属性名称,将 ValueMember 设置为要用作列表可见字符串的属性名称ComboBox.Text。
然后你可以将ComboBox.Text设置为ComboBox.SelectedValue.ToString()(SelectedValue,因为SelectedItem,是一个object,你需要转换它。你知道它是一个字符串,所以只需转换它)。
ComboBox.Text 必须在一小段延迟后设置(在控件已经自行更改文本之后)。这可以通过调用Control.BeginInvoke() 来完成,并使用一个将文本更改为我们需要的操作。
使用简单的类对象来存储值:
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.DisplayMember = "CountryAndCode";
comboBox1.ValueMember = "Code";
comboBox1.DataSource = countryCodes;
comboBox1.SelectedIndex = -1;
comboBox1.SelectedIndexChanged += (o, ev) => {
if (comboBox1.SelectedIndex < 0) return;
comboBox1.BeginInvoke(new Action(() => {
comboBox1.Text = comboBox1.SelectedValue.ToString();
}));
};
}
public List<CountryCode> countryCodes = new List<CountryCode>() {
new CountryCode() { Country = "USA", Code = "+1" },
new CountryCode() { Country = "Canada", Code = "+1" },
new CountryCode() { Country = "Argentina", Code = "+54"},
new CountryCode() { Country = "Brasil", Code = "+55"}
};
类定义:
public class CountryCode
{
public CountryCode() { }
public string Country { get; set; }
public string Code { get; set; }
public string CountryAndCode => this.ToString();
public override string ToString() => this.Country + (char)32 + this.Code;
}
注意:comboBox1.SelectedItem是一个CountryCode类对象。您只需将其转换为 CountryCode 即可读取此项目的所有属性。
var item = comboBox1.SelectedItem as CountryCode;
string selectedName = item.Country;
string selectedCode = item.Code; // etc.
如果您想保留简单的字符串格式,可以使用List<string>。
这或多或少是一样的(除了灵活性的损失)。您可以从 ComboBox.SelectedItem 中提取国家代码,使用 string.LastIndexOf() 来确定 + 字符在字符串中的位置:
private List<string> simpleCountryCodes = new List<string>() {
"USA +1", "Canada +1", "Argentina +54", "Brasil +55"
};
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.DataSource = simpleCountryCodes;
comboBox1.SelectedIndex = -1;
comboBox1.SelectedIndexChanged += (o, ev) => {
if (comboBox1.SelectedIndex < 0) return;
string item = comboBox1.SelectedItem.ToString();
string code = item.Substring(item.LastIndexOf("+"));
comboBox1.BeginInvoke(new Action(() => { comboBox1.Text = code; }));
};
}
如果您决定将 List<string> 转换为 List<CountryCode>,您可以使用 LINQ 生成 CountryCode 对象像这样的字符串:
var countryCodes = new List<CountryCode>();
countryCodes.AddRange(simpleCountryCodes.Select(c => new CountryCode() {
Code = c.Substring(c.LastIndexOf("+")),
Country = c.Substring(0, c.IndexOf("+") - 1)
}).ToArray());
在这两种情况下都是这样工作的: