Reputation: 29159
I have the following code, The model class X
will be filled from a database table with a composite key. The service layer method returns a list of X
.
I want the drop down list shows values of A + "-" + B + "-" + C
. How to set the ValueMember
and DisplayMember
of the combo box? Do I need to transform List<X>
to a list of new class with an added property shows A + "-" + B + "-" + C
? Can object reference be used as value members?
class X // A, B, C are key in the database table
{
string A { get; set; }
string B { get; set; }
string C { get; set; }
....
}
List<X> GetListOfX() { ..... } // from service layer
var l = GetListOfX();
ComboBox1.DataSource = l; // Or convert it to bindsource?
ComboBox1.DisplayMember = "?"; // How to display A + "-" + B + "-" + C?
ComboBox1.ValueMember = "?"; // Should it not be set so it uses the object reference?
Upvotes: 0
Views: 105
Reputation: 37770
Do I need to transform List
Option 1. Override object.ToString
method.
class X // A, B, C are key in the database table
{
string A { get; set; }
string B { get; set; }
string C { get; set; }
....
public override string ToString()
{
return string.Format("{0}-{1}-{2}", A, B, C);
}
}
var l = GetListOfX();
ComboBox1.DataSource = l; // that's all, you don't need to set value member or display member
Option 2. Make a sort of "view model class" (that is, transform X
instances into another type).
class X_ViewModel
{
public X Model { get; private set; }
public X_ViewModel(X model)
{
Model = model;
}
string DisplayName
{
get { return string.Format("{0}-{1}-{2}", A, B, C); }
}
....
}
var l = GetListOfX().Select(x => new X_ViewModel(x)).ToList();
ComboBox1.DataSource = l;
ComboBox1.DisplayMember = "DisplayName";
ComboBox1.ValueMember = "Model";
Personally, I prefer option 2, but it really depends on complexity of X
, and other use-cases, applicable for X
instances.
Upvotes: 1