在下拉列表中连接要显示的两个字段
我想从列表中连接两个字段以显示在下拉列表中。 以下是我正在尝试使用的代码。我不想改变我的产品的模型,所以我试图做下面的事情,但我无法想出任何东西,没有构建我自己的对象与字段连接。在下拉列表中连接要显示的两个字段
skuDropDown.DataSource = List<product>
skuDropDown.DataTextField = "ProductId" // want to combine with"Description";
skuDropDown.DataValueField = "ProductId";
skuDropDown.DataBind();
感谢任何想法会有所帮助。
要分配源给你的方法,我会去使用LINQ创建一个你想要的属性的匿名类型。类似于
List<Product> products = new List<Product>();
products.Add(new Product() { ProductId = 1, Description = "Foo" });
products.Add(new Product() { ProductId = 2, Description = "Bar" });
var productQuery = products.Select(p => new { ProductId = p.ProductId, DisplayText = p.ProductId.ToString() + " " + p.Description });
skuDropDown.DataSource = productQuery;
skuDropDown.DataValueField = "ProductId";
skuDropDown.DataTextField = "DisplayText";
skuDropDown.DataBind();
谢谢,这个工作很喜欢,一旦我把它搞砸了 – Locke12 2010-05-26 21:29:08
创建一个扩展产品的新类,将List内容强制转换为扩展类,该扩展类包含一个新属性,该属性返回ProductID和Description的连接值。
我认为应该工作OTOMH。
我知道你不想改变产品结构,这就是为什么我建议做一个扩展类。但是如果没有将它绑定到对象的某个字段上,它是不可能的。
不幸的是,如果您使用的是数据绑定,那么DataTextField必须是数据源中字段的名称。
你可以做的一件事是在你绑定它们并修改它们的Text属性后迭代下拉列表中的项目。唯一要做的其他事情是将连接字段添加到数据对象中。
你可以这样做:
List<Product>.ForEach(
x => skuDropDown.Items.Add(
new Item(x.ProductId + " " x.ProductDescription, x.ProductId)
);
通过名单只是循环和每个项目添加到下拉列表中。这就是.net会在你的例子中幕后为你做的。
您只需重写产品的.ToString()方法。
public override string ToString()
{
return ProductID + " " + ProductDescription;
}
然后你需要做的就是绑定到下拉菜单。根据我的理解,下拉标签绑定到绑定到集合中的对象的tostring()。
换句话说,这样做。
List<Product> products = new List<Product>();
products.Add(new Product() { ProductId = 1, Description = "Foo" });
products.Add(new Product() { ProductId = 2, Description = "Bar" });
var productQuery = products.Select(p => new { ProductId = p.ProductId, DisplayText = p.ProductId.ToString() + " " + p.Description });
skuDropDown.DataSource = productQuery;
skuDropDown.DataBind();
,如果你有一个类来表示一个产品,只是创建扩展类的属性,并返回其组合,例如:
public string ID_Description {
get
{
return string.Format("{0} ({1})", Name, ProductId);
}
}
,并在你的数据绑定下拉列表中引用你的财产
skuDropDown.DataSource = productQuery;
skuDropDown.DataValueField = "ProductId";
skuDropDown.DataTextField = "ID_Description";
skuDropDown.DataBind();
恐怕你没有别的选择,只能扩展域名 – 2010-05-26 20:34:58