0

For example I have a web control being created the following way:

<dnwc:TestControl runat="server" CurrentSite="test"></dnwc:TestControl>

How would I get the value of CurrentSite in code behind(TestControl.cs)? I tried to get the value by doing:

this.Attributes["CurrentSite"]

But the value is null.

SOLUTION:

Since i can't post an answer, I will add it here.

I had to declare the attribute in the TestControl.cs file:

public string CurrentSite
    {
        get
        {
            string s = (string)ViewState["CurrentSite"];
            return (s == null) ? "test2" : s;
        }
        set
        {
            ViewState["CurrentSite"] = value;

            //Retrieve the current site and set it as an attribute in the input tag
            inputTag.SetAttribute("data-current-site", value);
        }
    }

Unfortunately I could only access the value after it has been set. The value gets set after the instance has been created. So after the constructor gets called. Originally I needed the value to be set in a method that the constructor calls but this will do for now.

pmaj
  • 51
  • 7

1 Answers1

2

1) Give an ID to the WebControl

<dnwc:TestControl runat="server" CurrentSite="test" ID="testControl"></dnwc:TestControl>

2) You can use the Page.FindControl(string id) to get the Control from the Page code behind

Control webcontrol = FindControl("testControl");

2) Cast the Control to TestControl and get the CurrentSite property value.

string currentSite = ((TestControl)webcontrol).CurrentSite;
Fals
  • 6,813
  • 4
  • 23
  • 43