Aloha
I have a custom control that I need to create from a class and add to the page. My class has a function through which I pass Pageso that I have access to the controls on the page. I use this method to add standard ASP controls already and all that it works as expected. My problem is that the type for the custom control is defined as defined?
I read here to move .cs from the control to the App_Code folder, but when I do this, it will not compile since it does not see the controls in ascx as valid. For example, I get CS0103: The name 'litTest' does not exist in the current context. Since they are partial classes, I created a new empty partial class in the App_Code folder and left only the .cs file. Control
Well, it compiles this way, but when I add the control to the Page.controls collection, I don't see anything on the page where it should be. For example, I added TESTan ascx file to the end of the file, I do not see it on the page. In addition, the control has variables that I need to set so that I do not have access to use an empty partial class.
I know that what I'm trying to do works with standard controls, why can't I get this to work with a custom control?
My partial class in the App_Code folder:
public partial class CustomControlClass : System.Web.UI.UserControl
{
}
My partial class for user control:
public partial class CustomControlClass : System.Web.UI.UserControl
{
private int _myValue= -1;
public int myValue
{
get { return _myValue; }
set { _myValue= value; }
}
protected void Page_Init(object sender, EventArgs e)
{
litTest.Text = "TEST";
}
}
My ascx user interface:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CustomControlClass.ascx.cs" Inherits="CustomControlClass" %>
<asp:Literal ID="litTest" runat="server"></asp:Literal>
TEST
My class is App_Code:
public class MyClass
{
public static void doWork(Page Ctrl)
{
CustomControlClass c = new CustomControlClass();
Ctrl.Controls.Add(c);
Literal l = new Literal();
l.Text = "HELLO";
Ctrl.Controls.Add(l);
}
}
The word TEST is not displayed on the page output. The word "HELLO" appears just fine. I tried calling MyClass.doWork()from pages Load, Initand PreInitcallbacks, they all lead to a date.
Update:
As Min Nguyen said, I can use the Ctrl.LoadControl("~/Controls/CustomControlClass.ascx");control to load, but I cannot use it as my own type. I have to assign it as a control type:
Control c= Ctrl.LoadControl("~/Controls/CustomControlClass.ascx");
. , - . , :
c.GetType().GetProperty("myValue").SetValue(c, 1, null);
, , . , , .
, , .