Search code examples
c#.netwindowsformsintegration

Large string in label causing application to hang (C# Windows)


I am having an windows application where I am fetching data from db and binding that to a label. I am using timer and scrolling the label, this works fine when the string is around 150 characters but when I have string of around 30000 characters it just hangs out the application.

       lblMsg1.AutoEllipsis = true;
  private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (lblMsg1.Right <= 0)
                {
                    lblMsg1.Left = this.Width;
                }
                else
                    lblMsg1.Left = lblMsg1.Left - 5;

                this.Refresh();
            }
            catch (Exception ex)
            {

            }
        }

public void bindData()
{
lblMsg.Text = "Some Large text";
}

 public void Start()
        {
            try
            {
                timer1.Interval = 150;
                timer1.Start();
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
            }
        }

Why is this related to string length and causing application to hang? Thanks in advance.


Solution

  • I guess you are trying to create a news ticker? I am not sure that labels are designed to hold such big strings. Use a picturebox instead and update your code.

    Define two variables in your form class. One to hold text offset and the other to hold the graphics object for the picture box. Like this:

    private float textoffset = 0;
    System.Drawing.Graphics graphics = null;
    

    In the form onload do this:

    private void Form1_Load(object sender, EventArgs e)
    {
        textoffset = (float)pictureBox1.Width; // Text starts off the right edge of the window
        pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
        graphics = Graphics.FromImage(pictureBox1.Image);
    }
    

    Your timer should then look like this:

    private void timer1_Tick(object sender, EventArgs e)
    {
        graphics.Clear(BackColor);
        graphics.DrawString(newstickertext, new Font(FontFamily.GenericMonospace, 10, FontStyle.Regular), new SolidBrush(Color.Black), new PointF(textoffset, 0));
        pictureBox1.Refresh();
        textoffset = textoffset-5;
    }