2013-04-30 98 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