First off, I am wondering if this is possible. I read slight grumblings around the internet about this, but I was not entirely sure.
My scenario: I have a base chart class which has some methods which all charts should have.
public partial class BaseChart : System.Web.UI.UserControl
{
public BaseChart()
{
}
public void ToggleLegend()
{
Chart1.Legends[0].Enabled = !Chart1.Legends[0].Enabled;
}
}
There is also some mark-up for this BaseChart -- setting background colors, etc. All charts which inherit BaseChart should use this starting mark-up and be able to build upon it.
I would then like to do this:
public partial class HistoricalLineChart : BaseChart
{
public HistoricalLineChart()
: base()
{
}
public HistoricalLineChart(int reportID)
: base()
{
Chart1.Titles[0].Text = "Hello World";
}
}
where HistoricalLineChart is a web user control with no mark-up e.g. "HistoricalLineChart.ascx"
The problem is that Chart1 is undefined when in HistoricalLineChart's scope. Is there something that I am missing here?
Thanks.
Unfortunately the markup portion of
BaseChart
is not actually part of theBaseChart
class. The markup is part of a class that gets created when you compile and it inherits fromBaseChart
. SoHistoricalLineChart
only contains what you've explicitly set inBaseChart
and none of the markup. The only way I know to work around this is to use a Composite Control or Custom Server Control (vs a UserControl).It's a bit more of a pain since you have to add your child controls programmatically, but should do what you want.Here is an example: http://msdn.microsoft.com/en-us/library/3257x3ea(v=VS.100).aspx
Basically:
CompositeControl
.CreateChildControls
. In this method, you can add all of your child controls (like your chart).Render
. Override this if you need custom markup in addition to the child controls. You can output your custom markup plus callRenderControl
on all of your child controls to tell them where to render their output. If you don't override this method at all, then the composite control will render out the child controls in the order that they are in the controls collection.Here are a couple more tutorials: