c# - 在 C# 中动态添加一个字段到集合?

标签 c# asp.net string data-binding

我有一些基本的下拉列表数据绑定(bind)代码。我需要在运行时修改数据源并插入一个新字段。

  ddlPrimaryCarrier.DataSource = FinancialInstitutions;
            ddlPrimaryCarrier.DataValueField = "EntityCode";
            ddlPrimaryCarrier.DataTextField = "EntityNameDesc";
            ddlPrimaryCarrier.DataBind();

我实际上想在集合中添加一个字段,该字段是描述和代码的格式化字符串。喜欢...

var newField = string.Format("({0}) - {1}", "EntityCode", "EntityNameDesc");

然后

ddlPrimaryCarrier.DataTextField = "newField";

正确的做法是什么?我可以遍历现有集合并使用我需要的字段创建一个新的匿名类型列表吗?任何人有任何关于如何做到这一点的例子吗?

谢谢, ~ck 在圣地亚哥

最佳答案

此处最简单的方法是向类型添加一个属性。如果这是生成的(可能是 EF 等),则使用 partial class:

namespace Whatever {
    partial class FinancialInstitution {
        public string EntityCaption {
            get {return "(" + EntityCode + ") - " + EntityNameDesc;
        }
    }
}

如果这是一个 DataTable,您可以添加一个计算列。如果这是您无法控制的类型,可能使用自定义类型描述符(通过 TypeDescriptionProvider)执行此操作(直接针对该类型),但它是很难。相反,我宁愿封装实例,添加模拟封装类的直通属性,并添加新的属性:

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;
    }
}

并改为绑定(bind)到垫片上。

关于c# - 在 C# 中动态添加一个字段到集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1909083/

相关文章:

c# - 如何从 CDATA 中删除 href 标签

c# - 使用MCI从内存中播放avi流

c# - 重复初始化 Clearscript V8 引擎时内存不足(GC 问题?)

c# - 如何修复以下代码示例的 Fortify 扫描报告中的 ‘Path Manipulation’ 问题

c# - 更改 DropDownList 项取决于另一个 DropDownList(OnChange 事件)ASP.NET 网页中的值

c# - 从 2.2 迁移到 3.1 后 EF Core 出现问题

C# .net Core - 获取磁盘上的文件大小 - 跨平台解决方案

c# - 加快字符串连接速度

c - 为什么字节顺序(endianess)对于标准 C 字符串来说不是问题?

c - 在c中制作一个将小写字符串转换为大写字符串的函数