2011-11-24 72 views
1

我将数据绑定到一个下拉列表对的列表,由于某种原因它不工作,我是感兴趣。DataBinding:'System.Web.UI.Pair'不包含名称为'First'的属性

我使用的代码是:

public void BindDropDown(List<Pair> dataList) 
{ 
    ddlGraphType.DataTextField = "First"; 
    ddlGraphType.DataValueField = "Second"; 

    ddlGraphType.DataSource = dataList; 
    ddlGraphType.DataBind(); 
} 

我得到这个例外,这是骗人的!

DataBinding: 'System.Web.UI.Pair' does not contain a property with the name 'First'. 

在此先感谢。

新增

我知道异常意味着什么,但一对对象不包含第一,第二属性,这就是问题所在。

回答

8

FirstSecond是不属于Pair类型的字段。你需要创建一个类具有两个属性:

public class NewPair 
{ 
    public string First { get; set; } 
    public string Second { get; set; } 
} 

编辑:的Tuple使用:@Damien_The_Unbeliever &建议@克里斯Chilvers

List<Tuple<string, string>> list = new List<Tuple<string, string>>() 
{ 
    new Tuple<string,string>("One","1"), 
    new Tuple<string,string>("Two","2"), 
}; 

ddlGraphType.DataTextField = "Item1"; 
ddlGraphType.DataValueField = "Item2"; 

ddlGraphType.DataSource = list; 
ddlGraphType.DataBind(); 
+1

或者,在.NET 4可以使用元组<字符串,字符串> –

+1

对于.NET 4或更高,'元组'可能是一个合适的替代 - 它确实实现的属性而不是字段。 –

+0

不错的克里斯和达米安! – ThePower

0

Theat表示目标属性必须是依赖属性。这也意味着你不能绑定字段和Pair.First是场不财产

0
public sealed class Pair 
{ 
} 

领域:

Public field First Gets or sets the first object of the object pair. 
Public field Second Gets or sets the second object of the object pair. 

MSDN

0

在声明属性后,可能已经忘记了{get; set;}

public class A 
{ 

    //This is not a property 
    public string Str; 

//This is a property 
    public string Str2 {get; set;} 

} 
相关问题