Search code examples
c#asp.netpropertieswebformsweb-user-controls

How to create key-value pair property in web user control


I want to pass list of values to web user control from page.

Something like this:

<uc:MyUserControl runat="server" id="MyUserControl">
    <DicProperty>
        <key="1" value="one">
        <key="2" value="two">
               ...
    </DicProperty>  
</uc:MyUserControl>

How to create some kind of key-value pair property (dictionary, hashtable) in web user control.


Solution

  • I have found one kind of solution:

    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; }
        }
    }
    

    And on the page:

    <%@ 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>