public partial class TestConrol : UserControl
{
public TestConrol()
{
InitializeComponent();
}
public override string ToString()
{
return "asd";
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TestConrol tc1 = new TestConrol();
comboBox1.Items.Add(tc1);
TestConrol tc2 = new TestConrol();
comboBox1.Items.Add(tc2);
}
}
加载表单时,我看到组合框有两个名称为空的项目,而不是“asd”:/
但是,如果我在公共(public)类中重写 ToString() 而不是派生自任何东西,则此方法有效:
public class TestClass
{
public override string ToString()
{
return "bla bla bla";
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TestClass tcl = new TestClass();
comboBox1.Items.Add(tcl);
}
}
之后我在组合框中看到“bla bla bla”
最佳答案
在您的控件中创建一个属性并将组合框的 DisplayMember 映射到该属性,它应该可以工作。
关于c# - 为什么重写的 ToString() 在项目添加到 ComboBox 时不返回我想要的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15885784/