DropDownList的DataTextField从性质组成? [英] dropdownlist DataTextField composed from properties?

查看:163
本文介绍了DropDownList的DataTextField从性质组成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过一个对象的多个属性组成的C#,使DropDownList的datatextfield财产asp.net?

is there a way to make the datatextfield property of a dropdownlist in asp.net via c# composed of more than one property of an object?

public class MyObject
{
  public int Id { get; set; }
  public string Name { get; set; }
  public string FunkyValue { get; set; }
  public int Zip { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
  List<MyObject> myList = getObjects();
  ddList.DataSource = myList;
  ddList.DataValueField = "Id";
  ddList.DataTextField = "Name";
  ddList.DataBind();
}

我想如不能用名,而是名称(邮编),例如。

I want e.g. not use "Name", but "Name (Zip)" eg.

当然,我可以改变MyObject的类,但我不希望这样做(因为为MyObject类是模型类,不应该做的事情我需要在UI)。

Sure, i can change the MyObject Class, but i don't want to do this (because the MyObject Class is in a model class and should not do something what i need in the UI).

推荐答案

另一个属性添加到MyObject来类,并绑定到该属性:

Add another property to the MyObject class and bind to that property :

public string DisplayValue
{
 get { return string.Format("{0} ({1})", Name, Zip); }
}

或者,如果你不能修改为MyObject,创建在presentation层(只用于显示)的包装对象。这也可以使用一些LINQ完成的:

Or if you can not modify MyObject, create a wrapper object in the presentation layer (just for displaying). This can also be done using some LINQ:

List<MyObject> myList = getObjects();
ddList.DataSource = (from obj in myList
                    select new
                    {
                      Id = obj.Id,
                      Name = string.Format("{0} ({1})", obj.Name, obj.Zip)
                    }).ToList();
ddList.DataValueField = "Id";
ddList.DataTextField = "Name";
ddList.DataBind();

(抱歉,我没有Visual Studio中可用,所以有可能在code错误)

(sorry I don't have Visual Studio available, so there might be errors in the code)

这篇关于DropDownList的DataTextField从性质组成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆