Stupid Chart Tricks
The new free Chart Control from Microsoft is awesome (for download details see my original post here). But if you can avoid being dazzled by the plethora of charting features, you may realize it can be used for other tasks.
You can use the Chart Control to display simple text dynamically in a bitmap.
You don't need to do any plotting to use the control.
- Drop a Chart onto a page.
- Delete all the sub-elements inside the Chart Element:
- In the properties windows, add and configure the Titles you wish to display. Make sure to give each title a descriptive name so you can access it from code-behind.
<asp:Chart ID="Chart1" runat="server">
</asp:Chart>
Here is what the demo markup looks like:
<asp:Chart ID="ChartTextOnly" runat="server"
BackColor="Transparent"
Height="80px"
Width="612px"
EnableViewState="True">
<Titles>
<asp:Title BackColor="ForestGreen"
BackGradientStyle="LeftRight"
BackSecondaryColor="Blue"
Font="Forte, 16pt"
ForeColor="Yellow"
Name="MainTitle"
Text="Congratulations, you have logged in successfully!"
BorderColor="Black"
ShadowOffset="5">
</asp:Title>
<asp:Title Name="Spacer"
BackColor="Transparent"
Font="Courier New, 4pt"
Text=" ">
</asp:Title>
<asp:Title Alignment="MiddleLeft"
BackColor="Transparent"
Font="Lucida Calligraphy, 10pt"
Name="Date"
Text="Star Date"
TextStyle="Frame">
</asp:Title>
</Titles>
</asp:Chart>
Here is what the code-behind, that dynamically updates the text, looks like:
public partial class _Default : System.Web.UI.Page
{
string UserName = "Matilda";
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false) // first time only
{
ChartTextOnly.Titles["MainTitle"].Text =
String.Format("Congratulations {0}, you've logged in successfully!",
UserName);
ChartTextOnly.Titles["Date"].Text = "On Star Date: " +
DateTime.Now.ToLongDateString();
}
}
And here is what the final product looks like (pretty sexy, eh?):
I know what the smart people are thinking: "Now hold on there Sparky, sure it looks cool, but if the server has to render a new graphic on every page post-back, my users are going to have me tied to a post, stripped to the waist and horse-whipped."
That's true. And I would be the first in line. So, to avoid rendering the image on every post-back, set the ViewState of the chart to true.
Notes:
This is useful if you need to display text that you don't want people to copy and paste. It's like a poor man's Captcha .
Any font can be used. Since the text is rendered at the server, it will be exact and not dependent upon the client machine's fonts.
I thought the space between the two titles was insufficient so I created a third title between them to be a spacer. The height of the space is controlled by the font size of the empty string.
I hope you find this useful.
Steve Wellens