我有这个方法可以将 Conta
实例添加到名为“comboContas”的 ComboBox
中:
public void AdicionaConta(Conta novaConta)
{
comboContas.Items.Add(novaConta);
comboContas.DisplayMember = "Titular";
}
请注意,我已将 DisplayMember
属性设置为“Titular”。这是我的 Conta
类:
public abstract class Conta
{
public int Numero { get; set; }
public double Saldo { get; set; }
public Cliente Titular { get; set; }
public override string ToString()
{
return "titular: " + this.Titular.Nome;
}
}
现在,“Titular”属于Cliente
类型。
这是 Cliente
类:
public class Cliente
{
public string Nome { get; set; }
public string Rg { get; set; }
public Cliente(string nome)
{
this.Nome = nome;
}
public override string ToString()
{
return "ToString do Cliente: " + this.Nome;
}
}
我想在“comboContas”组合框中显示的内容类似于“ToString do Cliente: Gabriel”。
但是,未调用 Cliente
类的 ToString
方法。相反,被调用的是来自 Conta
类。
这是非常简单的事情,我真的不知道发生了什么。如果我将 DisplayMember
更改为任何其他属性,它将起作用。如果我将“Titular”属性的类型更改为任何其他类型,则会调用此其他类型的 ToString()
。它只是不适用于 Cliente
。
最佳答案
您的代码有问题(在每次添加之后而不是提前设置?)因为它确实按预期工作。检查一下:
using System;
using System.Windows.Forms;
namespace Tests
{
public class Conta
{
public int Numero { get; set; }
public double Saldo { get; set; }
public Cliente Titular { get; set; }
public override string ToString()
{
return "titular: " + this.Titular.Nome;
}
}
public class Cliente
{
public string Nome { get; set; }
public string Rg { get; set; }
public Cliente(string nome)
{
this.Nome = nome;
}
public override string ToString()
{
return "ToString do Cliente: " + this.Nome;
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new Form { Padding = new Padding(16) };
var comboBox = new ComboBox { Dock = DockStyle.Top, Parent = form };
comboBox.DisplayMember = "Titular";
comboBox.Items.AddRange( new []
{
new Conta { Titular = new Cliente("Victor") },
new Conta { Titular = new Cliente("Mauricio") },
new Conta { Titular = new Cliente("csni") },
});
Application.Run(form);
}
}
}
结果:
关于c# - Combobox 中的 DisplayMember 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32658132/