A DataBound Javascript News Ticker for ASP.NET

4.2 (41 votes)

It's funny how requirements come along like buses in the ASP.NET forums - you suddenly get the same thing asked for by two or more people in quick succession. Recently, a couple of people asked for help creating a Javascript ticker, like the one at the top of the BBC News site, which displays a selected number of headlines drawn from a database. I had adapted the code from the BBC site to create a similar widget that displayed the most recent threads in a message board on an old Classic ASP site some time ago. It's about time I dusted it off and updated it for use in an ASP.NET application.

To keep things relatively simple, I've created the ticker as a User Control, which is the ASP.NET successor to my original Server-Side Include file. The ascx file will hold the Javascript and the ascx.cs file will contain the data access code. First the Javascript:


<script language="JavaScript" type="text/javascript">


var CharacterTimeout = 50;

var StoryTimeout = 3000;

var SymbolOne = '_';

var SymbolTwo = '-';

var SymbolNone = '';

var LeadString = 'LATEST:&nbsp;&nbsp;&nbsp;';

var Headlines = new Array();

var Links = new Array();

var ItemCount = 4;


<asp:Literal ID="MyTicker" runat="server" />


function startTicker() {

 StoryCounter = -1;

 LengthCounter = 0;

 TickerLink = document.getElementById("tickerlink");




function runTicker() {

 var Timeout;

 if (LengthCounter == 0) {


  StoryCounter = StoryCounter % ItemCount;

  CurrentHeadline = Headlines[StoryCounter];

  TargetLink = Links[StoryCounter];

  TickerLink.href = TargetLink;

  Prefix = "<span class=\"ticker\">" + LeadString + "</span>";



 TickerLink.innerHTML = Prefix + CurrentHeadline.substring(0, LengthCounter) + getSymbol();


 if (LengthCounter != CurrentHeadline.length) {


  Timeout = CharacterTimeout;


 else {

  LengthCounter = 0;

  Timeout = StoryTimeout;


 setTimeout("runTicker()", Timeout);



function getSymbol() {

 if (LengthCounter == CurrentHeadline.length) {

  return SymbolNone;


 if ((LengthCounter % 2) == 1) {

  return SymbolOne;


 else {

  return SymbolTwo;







The Javascript starts with a set of variables being defined. CharacterTimeout and StoryTimeout respectively set the delay between the addition of characters to the headline, and the next story appearing. Three symbols are created, which give the appearance of a typewriter or old-fashioned teletype running as characters are appended to the headline. Finally, and array is set for the headlines, and one for the links, followed by the total number of headlines that will be managed by the ticker.

Next, an asp:Literal control is added. This will serve as a placeholder for the array of headlines and links that will be retrieved from the database. This is followed by the three functions that do the brunt of the work:

startTicker() intialises the ticker by setting some counters to their starting values, and then it locates the <a> tag that will display the links. The <a> tag has not been added yet, but should appear at the top of the ascx file:



  <a id="tickerlink" href="#" style="text-decoration: none;"></a>



Finally, it calls the next function:

LengthCounter holds the current position within the current headline. If the headline has finished, or not been started at all, the counter is set to 0. The StoryCounter, which was initialised at -1 is set to 0, or the next headline in the array. The link that matches the headline is also referenced. Then the initial text in the ticker is picked up and set inside a <span> that holds a CSS class attribute so that it can be styled. Then the <a> link text is set to hold the current headline together with its link and a symbol retrieved using the getSymbol() function. Some checks are made to calculate whether the current headline has been written, or is in the process of being written, then the runTicker() function is called with the value of TimeOut having been ascertained.

This function is pretty simple. All it does is to alternate between symbols - either a hyphen or an underline - depending on whether the position reached within the string containing the headline is odd or even. If the end of the string hass been reached, the symbol is an empty string.

Last of all, the first function, startTicker() is called.

Now to the code-behind file for the user control:


StringBuilder sb = new StringBuilder();

string connect = ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString;

using (SqlConnection conn = new SqlConnection(connect))


  string query = "SELECT TOP 4 ArticleID, Headline FROM Articles ORDER BY ArticleID DESC";

  SqlCommand cmd = new SqlCommand(query, conn);


  using (SqlDataReader rdr = cmd.ExecuteReader())


    int i = 0;

    while (rdr.Read())


      sb.Append("Headlines[" + i.ToString() + "] = '" + rdr[1].ToString() + "';");

      sb.Append("Links[" + i.ToString() + "] = '/Article.aspx?ArticleID=" + rdr[0].ToString() + "';");





MyTicker.Text = sb.ToString();


This is very straightforward too. Remembering to reference System.Data.SqlClient, System.Text and System.Configuration, the code simply connects to a database and gets the most recent 4 headlines in the database together with their ID so that links can be written. While looping through a DataReader, a StringBuilder object is built up containing the text for the headlines and the links. This is set to generate an array for the headlines and one for the links to populate the ones that were instantiated in the Javascript earlier. Finally, the contents of the StringBuilder are passed to the Literal control in the ascx file. And that is it.

The Javascript above looks quite complex at first glance, but hopefully, you can now see that it actually very straightforward.


Date Posted:
Last Updated:
Posted by:
Total Views to date: 47855


- Prakash

I get the error that Headlines does not exist in current context.

In the above function runTicker(), can you directly use CurrentHeadline = Headlines[StoryCounter] ???

Headlines[] is server side variable, how can it be used directly into client side java script ?

- Mike

Hi Prakash,

Headlines[] is a javascript array. You will see that it is used in the javascript <script> block. I'm not sure where you got the idea that it is a server-side variable from.

- Raju

Hello...This is really great. Is there any way to make the Headlines to scroll from bottom to top instead of from left to right...? Thanks, Raju

- Mike


The article is about a ticker, not a scroller. You can find loads of examples of the type you are looking for by using Google to search for Javascript Scoller.

- Goran Hillborg

Great application!

Very useful indeed. I´m surprised there is nothing similar to find from the top .Net control vendors.

I have one small question though: Your example assumes that there are 4 records collected from the database, which also matches the ItemCount variable in the javascript. But I must set this variable to the sama as in the Sql query, or it won´t work. Do you have an easy suggestion to how I can make the number of rows/items dynamic?

Best Regards

- Mike


I would put an asp Literal control where the ItemCount is and then run a SELECT COUNT(*) on the database for the number of items that match the selection criteria. Set the value of the Literal to the result of the COUNT and away you go.

- Khader

am getting an error Error name 'MyTicker' does not exist in the current context what am missing?

- Mike


Sounds like you have your literal in a ContentPanel or some such. You need to use FindControl() to reference it.

- Goran Hillborg


I haven´t checked in for a while now, thanks for your suggestion. My solution was similar to yours. The only problem is this: The ticker on my page is only used when there are any headlines to show, and if I set ItemCount to "0" IE displays the error "'CurrentHeadLine' is null or not an object". Do you have any suggestions on how I can get rid of this?


- Rob Strong

This so cool. I am trying to get the itemcont to be the array length (number of rows in the headlines array) but I am not having much luck. Any suggestions? I am new to Javascript.

- Mike


You could make the call to startTicker() dynamic, in that once you have detected that there are headlines, you would print it to the browser - otherwise don't.

- Mike


Like I suggested to Goran, you need to get the number of items from server-side code. Where I have itemCount = 4, you would put a Literal Control and set the itemCount to whatever your server-side code tells you.

- Goran Hillborg

Thanks Mike,

That did the trick. I have a hidden literal that holds the ItemCount number, so I just put this in the code behind:

if (ltlCount.Text != "0")
ScriptManager.RegisterStartupScript(this, this.GetType(), "myScript", "startTicker();", true);
MyTicker.Text = sb.ToString();

- Sayed

sorry i get that error
Error Message: 'TickerLink' is null or not an object
can you please help me

- Yasser

i get that error
Error Message: 'TickerLink' is null or not an object
can you please help me

- Allan

Many thanks for posting this it, really good ticker and just what I needed.


- Naresh

This looks really great and useful.... This was the one I was searching for...

- mahmoud

thank you very much


first, thank you for the post, its usefull.
i'd like to 3 buttons next to the ticker (pause, play), next and previous. any idea?

- Craig

This is great, any idea how I could use two of these on a single page? I need to query two separate databases and display two tickers. I've tried using two separate web controls with all variables renamed, and two separate literal controls, but can't get them both to work at once. Any pointers?

- Mike


I'm working on a jQuery version of this article which will be ready in the next day using this: http://www.makemineatriple.com/jquery/ and a couple of other tickers/scrollers. Check back soon.

- Rachid

great article!! I use 2 pics to move the ticker from left to right. how can I change the code so that it moves from right to left?

- Mike


You will find that a lot easier to accomplish if you read my jQuery version of this article: http://www.mikesdotnetting.com/Article/138/jQuery-News-Scrollers-and-Tickers-with-a-ListView

- luke

is there any reason why the literal is inside of javascript? As coded above i am getting a compile error because of this

- Mike


The lietral is inside the javascript so that the content can be changed dynamically. As far as your error is concerned, having a Literal there shouldn't give you one. Your issue is probably unrelated. The code as-is worked fine when I wrote the article.

- Syamand

could you please put the complete file source code download link ...


- Hosein

It's Very Good!

Recent Comments

Rajasekar 24/11/2015 12:27
In response to Import Data From Excel to Access with ASP.NET
While use this code i'm facing on error: "Unrecognized Database format C:\mydabase.accdb" can any...

Parmod 24/11/2015 07:28
In response to ASP.NET 5 Project Basics
For a new learner (Fresher) in ASP.NET there is a issue Fresher have to learn two types of , old...

Robert 22/11/2015 21:35
In response to ASP.NET 5 By Numbers
I have to agree fully with Paul, this does sound like an entire mis-mash of technologies. Sort of in...

Christian 21/11/2015 15:46
In response to MVC 5 with EF 6 in Visual Basic - Creating an Entity Framework Data Model
Many thanks Mike to introduce me in the EF6 Code First way of thinking. Exactly what I need for my...

ax plains 20/11/2015 16:29
In response to Examining the Details and Delete Methods
Hello, really great tutorial for a beginner like me! Is it possible to have an explanation on how a...

Abdul Latif 20/11/2015 14:42
In response to Reading Excel Files Without Saving To Disk In ASP.NET
Could anyone please help me, I am getting : "OfficeOpenXml.ExcelPackage" does not contain a for...

Thomas 20/11/2015 09:44
In response to Cheat Sheet - .NET Framework Exceptions
Hey Mike, nice list. I've also checked your article on how you created the list, but is there any to...

Pramod Gagare 19/11/2015 11:18
In response to Date Formatting in C#

Robby 19/11/2015 08:16
In response to WebMatrix - Database Helpers for IN Clauses
Would it also be possible to override the default query and querysingle methods to include the azure...

Menja 18/11/2015 08:28
In response to Sessions and Shopping Carts
Thank you for a perfect description and that you show all the screenshot at the same time!!! It a...