This problem has been bugging me ever since we hit it the other day at work. It occurred when Al was trying to style a .NET Calendar using an external CSS file. In the properties of the Calendar you can specify the css class using the CssClass fields, these render correctly. However, there are a few properties such as DayStyle which have a default colour that renders in the ‘Style’ tag of the link. If the ForeColor is specified it does render that colour, if you don’t specify, it renders ‘black’. This effectively makes the CssClass field useless for setting the link colour.
After a quick Google, turns out this issue has been discovered some time ago, there is a custom Calendar control on CodeProject that attempts to solve the problem. Probably the best solution out there but just seems like a lot of effort to stop a default ‘Style’ tag from rendering.
So here is another alternative, which I’ll probably put into the ‘dodgy hack’ category. But it does to the job. Simply override the page/usercontrol/custom control’s Render() method, and string.Replace() it. Here's an example:
public class CalendarNoDefault : System.Web.UI.WebControls.Calendar
{
public CalendarNoDefault()
{
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
//open a temp stream to save rendered calendar html into
System.IO.MemoryStream memstr = new System.IO.MemoryStream();
System.IO.StreamWriter stream = new System.IO.StreamWriter(memstr);
HtmlTextWriter wt = new HtmlTextWriter(stream);
base.Render(wt);
wt.Flush();
memstr.Seek(0, System.IO.SeekOrigin.Begin);
//read back the html from memory
System.IO.StreamReader rd = new System.IO.StreamReader(memstr);
char[] bytes = new char[memstr.Length];
rd.ReadBlock(bytes,0,(int)memstr.Length);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.EnsureCapacity((int)memstr.Length);
sb.Append(bytes);
//remove the 'default' colour style,
//If DayStyle.ForeColor is set it renders that colour,
//if it is not set it
//renders "color:Black" in the style="" tag by default.
//Still looking for a better way to remove this
sb.Replace("color:Black",string.Empty);
writer.WriteLine(sb.ToString());
memstr.Close();
stream.Close();
rd.Close();
wt.Close();
}
}