2014-01-09 49 views
2

我發現了這個錯誤。這是很明顯的:我不是數據綁定到正確的複選框列表!我應該是數據綁定filterONTYPElist,但我數據綁定到filterONDATASETlist ...複製粘貼錯誤,對不起......CheckboxList忽略DataValueField和DataTextField

我有渲染的CheckBoxList如下:

enter image description here

這裏是處理數據綁定的代碼:

FilterOnTypeCheckboxList.DataSource = listCheckboxItems; 
FilterOnDatasetCheckboxList.DataValueField = "Value"; 
FilterOnDatasetCheckboxList.DataTextField = "Text"; 
FilterOnTypeCheckboxList.DataBind(); 

我的數據源是list<CheckBoxItem>。那類看起來如下,你可以清楚地看到有一個公共財產的價值和公共屬性text:

[Serializable] 
public class CheckboxItem 
{ 
    public string Text { get; set; } 
    public string Value { get; set; } 

    public CheckboxItem(string value, string text) 
    { 
     Value = value; 
     Text = text; 
    } 

    public override string ToString() 
    { 
     return "brompot"; 
    } 
} 

但由於某些原因,每個複選框文本和值使用的的ToString()方法CheckBoxItem類,而不是適當的屬性「值」和「文本」。

PS:我檢查了價值和checkboxitems對象的文字是不是字符串「brompot」 ......

這不是讓toString()方法返回文本或值的選項,因爲我想複選框的值是數值屬性和複選框(標籤)文本

回答

3

我跑了一個快速測試,這似乎按預期工作。 你能否提供更多的細節?另外,驗證我提供的代碼是否與您正在做的相似?

<div> 
    <asp:Button ID="btnBind" runat="server" Text="Bind" OnClick="btnBind_Click" /> 
    <asp:CheckBoxList ID="cbList" runat="server"></asp:CheckBoxList> 
</div> 


public partial class _Default : Page 
{ 
    protected void btnBind_Click(object sender, EventArgs e) 
    { 
     List<CheckboxItem> listCheckboxItems = new List<CheckboxItem>(); 
     listCheckboxItems.Add(new CheckboxItem("Val-1", "Item-1")); 
     listCheckboxItems.Add(new CheckboxItem("Val-2", "Item-2")); 
     listCheckboxItems.Add(new CheckboxItem("Val-3", "Item-3")); 
     listCheckboxItems.Add(new CheckboxItem("Val-4", "Item-4")); 
     listCheckboxItems.Add(new CheckboxItem("Val-5", "Item-5")); 

     this.cbList.DataSource = listCheckboxItems; 
     this.cbList.DataValueField = "Value"; 
     this.cbList.DataTextField = "Text"; 
     this.cbList.DataBind(); 
    } 
} 

[Serializable] 
public class CheckboxItem 
{ 
    public string Text { get; set; } 
    public string Value { get; set; } 

    public CheckboxItem(string value, string text) 
    { 
     Value = value; 
     Text = text; 
    } 

    public override string ToString() 
    { 
     return "brompot"; 
    } 
} 

enter image description here

+0

這正是我想要做的,只有我沒有看到該值或文本,但無論是通過返回toString()方法。如果我不指定toString()方法,C#需要返回「CheckBoxItem」的類名的默認的toString()方法。我可以忽略什麼? – user1884155

+0

這只是一個猜測,但嘗試刪除該類的[Serializable]標記。 –

0

我相信你的錯誤是因爲你的ToString()方法。

編輯是這樣,看看是否能解決問題:

[Serializable] 
public class CheckboxItem 
{ 
    public string Text { get; set; } 
    public string Value { get; set; } 

    public CheckboxItem(string value, string text) 
    { 
     Value = value; 
     Text = text; 
    } 

    public override string ToString() 
    { 
    return Text; 
    } 
} 
+0

感謝您的建議,但你提出的解決方案具有兩個值和文本框將成爲等於「文本」的問題。 – user1884155

相關問題