2013-04-30 100 views
0

我發現了一種使用鍵值的解決方案,但問題是,當我在.Cs上使用它時,如: MyUserControl1.Param.Key =「Area」; MyUserControl1.Param.Value =面積如何在.CS端設置Key-value對?

它不允許我這樣做......下面是代碼...

public partial class MyUserControl : System.Web.UI.UserControl 
{ 
    private Dictionary<string, string> labels = new Dictionary<string, string>(); 

    public LabelParam Param 
    { 
     private get { return null; } 
     set 
     { 
      labels.Add(value.Key, value.Value); 
     } 
    } 

    public class LabelParam : WebControl 
    { 
     public string Key { get; set; } 
     public string Value { get; set; } 

     public LabelParam() { } 
     public LabelParam(string key, string value) { Key = key; Value = value; } 
    } 
} 
If I use it aspx page like below it work fine: 

<%@ Register src="MyUserControl.ascx" tagname="MyUserControl" tagprefix="test" %> 

<test:MyUserControl ID="MyUserControl1" runat="server"> 
    <Param Key="d1" value="ddd1" /> 
    <Param Key="d2" value="ddd2" /> 
    <Param Key="d3" value="ddd3" /> 
</test:MyUserControl> 
+0

張貼嘗試使用屬性的代碼?閱讀此:http://stackoverflow.com/questions/2257829/access-child-user-controls-property-in-parent-user-control – Fabske 2013-04-30 11:26:25

+0

一個屬性只有一個公共setter和一個私人的getter實現總是返回null '是一種代碼味道。只需創建一個'SetParam'方法。 – 2013-04-30 11:40:09

+0

我讓getter也是公開的,但是仍然無法將值設置爲'param' – Sneha 2013-04-30 12:02:37

回答

0

當你像你提到的用你的帕拉姆屬性:

MyUserControl1.Param.Key = "Area" 
MyUserControl1.Param.Value = Area 

由於您正在訪問Param屬性的獲取部分,因此會出現錯誤。屬性的get部分的實現總是返回null,這會導致代碼失敗,並可能導致NullRefrenceException。

除此之外,您的控件在您的字典中包含多個keyvaluepairs,因此使用Param屬性訪問這些值沒有任何意義。

嘗試增加類似特性:

public IDictionary<string,string> Labels 
{ 
    get 
    { 
     return labels; 
    } 
} 

然後你就可以像訪問值:

myControl.Labels["Key"] = value; 
+0

嘿..Chiristian ...非常感謝。這是一個很大的幫助...它解決了我的問題...帽子關了.. – Sneha 2013-05-02 08:55:05