在 C# 中获取组合框文本 [英] Get the combobox text in C#
问题描述
我用枚举中的值填充了一个组合框.
I filled up a combobox with the values from an Enum.
现在组合框是文本吧?所以我使用了一个 getter 和一个 setter.我在阅读文本时遇到问题.
Now a combobox is text right? So I'm using a getter and a setter. I'm having problems reading the text.
代码如下:
public BookType type
{
get
{
return (BookType)Enum.Parse(typeof(BookType), this.typeComboBox.Text);
}
set
{
this.typeComboBox.Text = value.ToString();
}
}
出于某种原因,this.typeComboBox.Text
在我选择组合框上的项目时总是返回一个空字符串.
For some reason, this.typeComboBox.Text
always returns an empty string when I select an item on the combobox.
有人看到我做错了什么吗?
Does someone see what I'm doing wrong?
我得出的结论是问题出在时间上.我调用文本的时间点确实是在我更改组合框之后,但仍然在该值被解析为值之前.问题现在以不同的方式解决,感谢所有的想法.
I have come to the conclusion that the problem lies in timing. The point in time at which I summon the text is indeed after I changed the combobox, but still before that value is parsed as a value. Problem fixed in a different way now, thanks for all the ideas.
推荐答案
我刚刚创建了一个简单的 Windows 窗体,一切正常.这是代码.
I just created a simple windows form, and everything worked okay for me. Here is the code.
public enum Test
{
One, Two, Three
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.comboBox1.DataSource = Enum.GetNames(typeof(Test));
}
public Test Test
{
get
{
return (Test)Enum.Parse(typeof(Test), this.comboBox1.Text);
}
set
{
this.comboBox1.Text = value.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(this.Test.ToString());
this.Test = Test.Two;
MessageBox.Show(this.Test.ToString());
}
}
这篇关于在 C# 中获取组合框文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!