I am looking for "best-practices" to display the value of foreign-key in a BindingSource.
Sample data开发者_Go百科:
PetID---PetName---PetTypeID
1---Tom---1
2---Jerry---2
PetTypeID---PetType
1---Cat
2---Mouse
I have a Pet class and Pet form. The following code is on the Pet form to return data from the database as a Pet collection and bind the data:
private BindingSource PetBindingSource = new BindingSource();
PetBindingSource.DataSource = Pet.GetPets();
txtPetName.DataBindings.Add(new Binding("Text", PetBindingSource, "PetName"));
txtPetType.DataBindings.Add(new Binding("Text", PetBindingSource, "PetTypeID"));
With this current example, txtPetType will show the PetTypeID (1 or 2), but I want it to display the actual value (Cat or Mouse).
So, what are some best-practices to handle something like this? Add a new property to the Pet class? Join the two tables in the stored procedure to return the value? Other options?
Note: PetName is editable, while PetTypeID will be read-only in this instance, so I'd like to rule out a combo box.
Explanations, examples, reading resources would all be much appreciated!
A facade property is the easiest option - especially if it is readonly; just add a property (in a partial
class if the type is generated) that walks the relation. There are other routes, though. You can write a TypeConverter
and decorate the property with it; this is a pain for generated types, though (since you can't add an attribute to a member declared in a separate partial class file). You can also use custom property models (ICustomTypeDescriptor
/TypeDescriptionProvider
), but these would be massively overkill just for this.
I can expand on any of these as necessary... but most (except the first) are lots of work...
Yep, like Marc said, add a PetTypeName property to the Pet class, which queries the database (or whatever, I'm assuming database) and gets the PetType record from the PetTypeID:
public class Pet {
...
public string PetTypeName {
get {
PetType pt = getPetTypeById(PetTypeID); // this method is up to you to write, of course
return pt.Description;
}
}
...
}
Then instead of binding to PetTypeID, bind to this new PetTypeName property.
精彩评论