我试图在listBox中为文本着色为什么会得到ArgumentOutOfRange异常?

时间:2013-09-24 12:07:35

标签: c# winforms

这是班级:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace GatherLinks
{
    class ColorText
    {


        public static void Texts(RichTextBox box, string text, Color color)
        {
            box.SelectionStart = box.TextLength;
            box.SelectionLength = 0;

            box.SelectionColor = color;
            box.AppendText(text);
            box.SelectionColor = box.ForeColor;
        }

        public static void ColorListBox(List<string> data, DrawItemEventArgs e)
        {
            string strLeft = null;
            string strMid = "---";
            string strRight = null;
            if (data[e.Index].Contains(strMid))
            {
                int index = data[e.Index].IndexOf(strMid);
                strLeft = data[e.Index].Substring(0, index);
                strRight = data[e.Index].Substring(index + strMid.Length);
            }

            using (Font f = new Font(FontFamily.GenericSansSerif, 16, FontStyle.Regular))
            {
                float startPos;
                e.Graphics.DrawString(strLeft, f, Brushes.Red, e.Bounds.X, e.Bounds.Y);
                startPos = e.Graphics.MeasureString(strLeft, f).Width;
                e.Graphics.DrawString(strMid, f, Brushes.Black, e.Bounds.X + startPos, e.Bounds.Y);
                startPos = e.Graphics.MeasureString(strLeft + strMid, f).Width;
                e.Graphics.DrawString(strRight, f, Brushes.Green, e.Bounds.X + startPos, e.Bounds.Y);
            }
        }
    }
}

我正在使用ColorListBox方法。

在Form1中我有:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index == -1)
            {
            }
            else
            {

                ColorText.ColorListBox(data, e);

            }
        }

现在出现异常时:

我看到变量数据为count = 0 例外是在这一行:

if (data[e.Index].Contains(strMid))

Index was out of range. Must be non-negative and less than the size of the collection

System.ArgumentOutOfRangeException was unhandled
  HResult=-2146233086
  Message=Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
  Source=mscorlib
  ParamName=index
  StackTrace:
       at System.ThrowHelper.ThrowArgumentOutOfRangeException()
       at System.Collections.Generic.List`1.get_Item(Int32 index)
       at GatherLinks.ColorText.ColorListBox(List`1 data, DrawItemEventArgs e) in d:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\ColorText.cs:line 29
       at HardwareMonitoring.Form1.listBox1_DrawItem(Object sender, DrawItemEventArgs e) in d:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 394
       at System.Windows.Forms.ListBox.OnDrawItem(DrawItemEventArgs e)
       at System.Windows.Forms.ListBox.WmReflectDrawItem(Message& m)
       at System.Windows.Forms.ListBox.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
       at System.Windows.Forms.Control.WmOwnerDraw(Message& m)
       at System.Windows.Forms.Control.WmDrawItem(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
       at System.Windows.Forms.Control.DefWndProc(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ListBox.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  InnerException: 

如何修复它以便它不会再次抛出此异常?那是因为我从来没有向数据变量发送任何信息,所以它是count = 0,这就是出现异常的原因吗?

提前致谢。

编辑*

这是Form1中的backgroundworker dowork事件:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (true)
            {

                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    if (tempCpuValue >= (float?)nud1.Value || tempGpuValue >= (float?)nud1.Value)
                    {
                        soundPlay = true;
                        NudgeMe();
                    }
                    else
                    {
                        soundPlay = false;
                        stop_alarm = true;

                    }

                    tempCpuValue = Core.cpuView(pauseContinueDoWork,cpu,this,data,tempCpuValue,button1);
                    tempGpuValue = Core.gpuView(pauseContinueDoWork,data,tempGpuValue,button1);
                    this.Invoke(new Action(() => data = new List<string>()));
                    tempCpuValue = Core.cpuView(pauseContinueDoWork, cpu, this, data, tempCpuValue, button1);
                    tempGpuValue = Core.gpuView(pauseContinueDoWork, data, tempGpuValue, button1);
                    this.Invoke(new Action(() => listBox1.DataSource = null));
                    this.Invoke(new Action(() => listBox1.DataSource = data));



                    //listBox1.DataSource = data;

                }
            }
        }

我无法在任何地方找到我在列表中添加或放入内容的地方 另外,当我运行我的程序时,listBox为空。

可能这是异常的原因,因为数据是空的,当我正在做listBox1.DataSource = data时,实际上listBox是空的吗?

2 个答案:

答案 0 :(得分:1)

在检查索引值之前检查List的计数。

if (data.Count > e.Index)
{
    if (data[e.Index].Contains(strMid))
    {
        int index = data[e.Index].IndexOf(strMid);
        strLeft = data[e.Index].Substring(0, index);
        strRight = data[e.Index].Substring(index + strMid.Length);
    }

}

答案 1 :(得分:1)

请使用以下代码代替您的代码..

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   if (e.Index >=0 )
   {
      ColorText.ColorListBox(listBox1.Items.Cast<string>().ToList(), e);
   }
}

或者你仍然得到一个错误更改ColorListBox方法,代码如下:

public static void ColorListBox(List<string> data, DrawItemEventArgs e)
{
    string strLeft = null;
    string strMid = "---";
    string strRight = null;
    if (e.Index < data.Count)
    {
        if (data[e.Index].Contains(strMid))
        {
            int index = data[e.Index].IndexOf(strMid);
            strLeft = data[e.Index].Substring(0, index);
            strRight = data[e.Index].Substring(index + strMid.Length);
        }

        using (Font f = new Font(FontFamily.GenericSansSerif, 16, FontStyle.Regular))
        {
            float startPos;
            e.Graphics.DrawString(strLeft, f, Brushes.Red, e.Bounds.X, e.Bounds.Y);
            startPos = e.Graphics.MeasureString(strLeft, f).Width;
            e.Graphics.DrawString(strMid, f, Brushes.Black, e.Bounds.X + startPos, e.Bounds.Y);
            startPos = e.Graphics.MeasureString(strLeft + strMid, f).Width;
            e.Graphics.DrawString(strRight, f, Brushes.Green, e.Bounds.X + startPos, e.Bounds.Y);
        }
    }
}