如何在C#中仅显示ComboBox中项目的子字符串 [英] How to show only a substring of an item in a ComboBox in C#
问题描述
我在组合框
中有一些公司名称作为项目,例如:
I have some Company names as Items in a ComboBox
like this:
123 SomeCompany
始终在100到999之间的数字加上公司名称。
Always a number between 100 and 999 plus the company name.
现在,如果用户选择一个项目,我希望文本框仅显示数字,而不显示公司名称。公司名称仅在他放下ComboBox时才可见...
Now if the user selects an Item I want the TextBox to only show the number, not the company name. he company name should only be visible when he drops down the ComboBox...
我尝试设置 ComboBox1.Text = ComboBox.Text.Substring (0,3)
在SelectedIndexChanged-Event和TextChanged-Event中,但是它什么也没做,在ComboBox中总有一切...
I tried to set ComboBox1.Text = ComboBox.Text.Substring(0, 3)
in the SelectedIndexChanged-Event and the TextChanged-Event, but it didn't do anything, there was always everything in the ComboBox...
自动完成模式
设置为无
。
我做错了什么?
推荐答案
要始终设置值格式,可以使用Format事件(带有FormattingEnabled = true)
To always format the value, you could use the Format event (with FormattingEnabled = true)
private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
{
e.Value = e.Value.ToString().Substring(0, 3);
}
但是,如果您希望在显示下拉菜单时显示完整值,您可以暂时禁用格式设置:
But if you want the full value to be displayed when the dropdown is shown, you can temporarily disable the formatting:
private void comboBox1_DropDown(object sender, EventArgs e)
{
comboBox1.FormattingEnabled = false;
}
private void comboBox1_DropDownClosed(object sender, EventArgs e)
{
comboBox1.FormattingEnabled = true;
}
这篇关于如何在C#中仅显示ComboBox中项目的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!