简体   繁体   中英

Creating Custom Control Based on Settings in C#

What I want to do is to override Label control and do the followings:

I defined some key/value pairs in a custom xml file where I like to fetch Text property values of Label Controls and my setting xml file looks like the one below:

<label key="lblLabel1" value="Something"/>

When I create a new instance of my custom label control, I will only pass ID and it will find the matching ID key in settings file and set the Text according to what it finds.

And also I like to define my custom control in Source View as well such as below:

<ccontrol:CLabel ID="lblLabel1"/>

Here I only change set the ID property and Text should be coming from settings.xml file.

How can I do that?

While I too would suggest using resources, what you are asking for is fairly easy to do.

First store your key value pairs in appSettings (Web.config) Link: http://msdn.microsoft.com/en-us/library/610xe886.aspx

Then write a control something like this (untested):

using System;
using System.Configuration;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Web
{
    public class SpecialLabel : Label
    {   
        protected override void OnLoad (EventArgs e)
        {
            base.OnLoad (e);

            //get value from appsettings
            if(!string.IsNullOrEmpty(this.ID)) {
                Configuration rootWebConfig1 = WebConfigurationManager.OpenWebConfiguration(null);
                if (rootWebConfig1.AppSettings.Settings.Count > 0)
                {
                    KeyValueConfigurationElement customSetting = rootWebConfig1.AppSettings.Settings[this.ID];
                    if (customSetting != null)
                        this.Text = customSetting.Value;
                }
            }
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM