Question

Can someone help me to create my custom web user control to be render into a placeholder dynamically?

I just created a web user control which does not have code in the server side just design in the aspx because all the functionallity is client-side.

Web Control

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebControlDemo.ascx.cs" Inherits="Project1.Web.UI.WebControlDemo" %>
<div>
Blah blah blah blah
</div>

In another page

protected void button1_Click(object sender, EventArgs e)
{
   WebControlDemo wcd = new WebControlDemo();
   this.placeHolder1.Controls.Add(wcd);
}

But I can't see anything. So what so I need to add that can finally becomes rendered?

Was it helpful?

Solution

You shouldn't create User controls manually in code. You should use LoadControl method from Page object. Then it will initialize it correctly. Like this

protected void button1_Click(object sender, EventArgs e)
{
   WebControlDemo wcd = this.LoadControl("~/SomePath/WebControlDemo.ascx") as WebControlDemo;
   this.placeHolder1.Controls.Add(wcd);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top