I have some basic dropdownlist databinding code. I need to modi开发者_JAVA百科fy the datasource at Runtime and insert a new field.
ddlPrimaryCarrier.DataSource = FinancialInstitutions;
ddlPrimaryCarrier.DataValueField = "EntityCode";
ddlPrimaryCarrier.DataTextField = "EntityNameDesc";
ddlPrimaryCarrier.DataBind();
I actually want to add a field to the collection that is a formatted string of the description and the code. Like...
var newField = string.Format("({0}) - {1}", "EntityCode", "EntityNameDesc");
then
ddlPrimaryCarrier.DataTextField = "newField";
What is the correct way to do this? Can I loop through the exisiting collection and create a new list of anonymous types with the field I need? Anyone have any examples of how to do that?
Thanks, ~ck in San Diego
The simplest approach here is to add a property to the type. If this is generated (perhaps EF etc) then use a partial class
:
namespace Whatever {
partial class FinancialInstitution {
public string EntityCaption {
get {return "(" + EntityCode + ") - " + EntityNameDesc;
}
}
}
If this is a DataTable
, you could add a computed column. If this is a type outside of your control, it is possible to do this (directly to the type) using a custom type-descriptor (via TypeDescriptionProvider
), but it is very hard. I would instead prefer to encapsulate the instance, adding pass-thru properties that mimic the encapsulated class, and adding the new one:
class MyShim {
private readonly FinancialInstitution inner;
public MyShim(FinancialInstitution inner) {this.inner = inner;}
public string EntityCode { get {return inner.EntityCode;}}
public string EntityNameDesc { get {return inner.EntityNameDesc;}}
public string EntityCaption {
get {return "(" + EntityCode + ") - " + EntityNameDesc;
}
}
and bind to the shims instead.
Assuming that FinancialInstitutions
is a collection of FinancialInstitution
objects, add a new property to your FinancialInstitution
class :
public string DisplayName
{
get { return string.Format("({0}) - {1}", EntityCode, EntityNameDesc);
}
If it is a DataTable
, you can add a computed column :
FinancialInstitutions.Columns.Add("DisplayName", typeof(string), "'(' + EntityCode + ') - ' + EntityNameDesc");
In both cases, set the ComboBox
's DisplayMember
to "DisplayName"
精彩评论