Wednesday 9 November 2011

Scrolling News Web Control using ASP.Net and C#




Requirement: Need To make following tables in SQL Server Database, and put corresponding records in the tables.

News Table



create table TblNews
 (
  newsId  int  primary key identity(1,1) Not null, 
  NewsDescription varchar(50) Not null, 
  dateCreated datetime 
 )

In code behind page:
News.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillNews();
        }
    }

    private void FillNews()
    {
        // Fetch News Records from Database and Store in Datatable…
        SqlConnection Conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        String strQuery = "SELECT NewsDescription FROM TblNews";
        DataTable _dt = new DataTable();
        SqlDataAdapter _da = new SqlDataAdapter(strQuery,Conn);
        _da.Fill(_dt);

        string strNews = null;

        for (int i = 0; i < _dt.Rows.Count; i++)
        {
            strNews = strNews + _dt.Rows[i]["NewsDescription"].ToString();
            strNews = strNews + "  ||  ";
        }

        lblNews.Text = strNews;
    }




Which just prepare a connection with the database and get the newsTitle and dateCreated to scroll in the marquee in direction=’UP’. I have prepared a string which can be added dynamically in a table row to fit in appropriate table row, which generates scrolling news section with anchor (link) to open detail in the new window. Idea behind opening in new window to stick the user to same site. You can do following with the marquee and JavaScript functionality used in the same.
  • Can stop on mouseover of the link [OnMouseOver='this.stop();']
  • Can start on mouseout of the link [OnMouseOut='this.start();']
  • Can controll the speed of the scrolling [direction='up' scrollamount='2']

In Design page:
News.aspx


<table width="100%" cellspacing="0px" cellpadding="0px" class="NewsBgColor">
        <tr>
            <td class="Table_TD_Center">
                <marquee behavior="SCROLL" width="100%" scrolldelay="100″" onmouseover='this.stop();'
                    onmouseout="this.start();">
                    <asp:Label ID="lblNews" runat="server" Text="" CssClass="RedLabel"/>
                </marquee>
            </td>
        </tr>
    </table>



Thanx...................

3 comments:

  1. Thx for your gr8 post!..am a newbie in asp.net and would appreciate if you could clarify the codes that will fill:

    1. //Fill News Section
    2. // Fetch News Records from Database and Store in Datatable…

    Once Again, Thx for your input

    ReplyDelete
  2. check the code again....
    Thnx...........

    ReplyDelete