繁体   English   中英

我在尝试为listBox中的文本着色时收到ArgumentOutOfRange异常,为什么?

[英]Im getting ArgumentOutOfRange exception when trying to color text in a listBox why?

这是课程:

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为空吗?

在检查索引值之前,请检查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);
    }

}

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

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);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM