尝试在列表框中为文本着色时,我收到参数超出范围异常

本文关键字:参数 异常 范围 列表 文本 | 更新日期: 2023-09-27 18:32:30

这是类:

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 方法。

在表格 1 中,我有:

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 中的后台工作线程执行工作事件:

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

我找不到在列表中添加或放置某些内容的任何地方此外,当我运行我的程序时,列表框是空的。

这可能是异常的原因,因为数据是空的

,而且当我做listBox1.数据源=数据时,所以实际上listBox是空的?

尝试在列表框中为文本着色时,我收到参数超出范围异常

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

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

或者仍然收到使用以下代码更改颜色列表框方法的错误:

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