Display search value based on foreign key in bindingsource

I'm looking for "best practices" for mapping a foreign key value to a BindingSource.

Sample data:

PetID---PetName---PetTypeID
1---Tom---1
2---Jerry---2


PetTypeID---PetType
1---Cat
2---Mouse

      

I have a Pet and Pet class. The following code is in Pet form to return data from the database as a Pet collection and data binding:

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"));

      

In 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 for handling something like this? Add a new property to the Pet class? Join two tables in a stored procedure to return a value? Other options?

Note. The PetName is editable, while the PetTypeID will be read-only in this case, so I would like to exclude the combo box.

Concepts, examples, reading resources would be much appreciated!

+2


source to share


2 answers


The facade property is the easiest option - especially if it's read-only; just add a property (to the class partial

if that type is generated) that moves the relationship. There are also other routes. You can write TypeConverter

and decorate this property; this is a pain for the generated types (although you cannot add an attribute to a member declared in a separate partial class file). You can also use Custom Property Models ( ICustomTypeDescriptor

/ TypeDescriptionProvider

), but this will massively overkill just for that.



I can expand any of them as needed ... but most (other than the first) are a lot of work ...

0


source


Yes, as Mark said, add a PetTypeName property to the Pet class, which queries the database (or whatever, I assume the 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, it binds to this new PetTypeName property.

0


source







All Articles