2011-11-24 69 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;} 

} 
相關問題