繁体   English   中英

为什么我得到异常错误indexOutOfRangeException?

[英]Why im getting exception error indexOutOfRangeException?

在Form1构造函数中,我有:

if (System.IO.File.Exists(keywords_path_file))
            {
                ListBoxLoadKeys(LocalyKeyWords, keywords_path_file);
            }
            else
            {
                fileExist = new StreamWriter(keywords_path_file);
                fileExist.Close();
                ListBoxLoadKeys(LocalyKeyWords, keywords_path_file);
            }

我使用断点并看到该文件存在:

C:\Users\bout0_000\AppData\Local\GatherLinks\GatherLinks\Keywords\Keywords.txt

文件内容是:

http://www.walla.co.il,walla
http://www.cnet.com,cnet
http://rotter.net/forum/scoops1/29961.shtml,rotter
http://vanessawest.tripod.com/crimescenephotos.html,VanessaWest
http://rotter.net/forum/scoops1/45227.shtml,scoops
https://www.google.com/search?q=live+cameras,live camera
https://www.google.com/search?q=rape+images&oq=+images&aqs=chrome..69i57.1661j0&sourceid=chrome&ie=UTF-8,hi
https://www.google.com/search?q=+images&um=1&ie=UTF-8&hl=en&tbm=isch&source=og&sa=N&tab=wi&ei=GqotUv2kA4OftAae94DoAg&biw=951&bih=457&sei=oaotUtDqM8WbtAag3IFg#hl=en&q=+and+&tbm=isch&um=1,chud
http://www.test.com,test

该文件包含9个键和关键字。 左侧键是右侧的关键字。

然后进入这个方法:

private void ListBoxLoadKeys(Dictionary<string, List<string>> dictionary, string FileName)
        {
            List<string> urls = new List<string>();
            using (StreamReader sr = new StreamReader(FileName))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    int i = line.Count();
                    tokens = line.Split(',');
                    dictionary.Add(tokens[0], tokens.Skip(1).ToList());
                    data.Add("Url: " + tokens[0] + " --- " + "Localy KeyWord: " + tokens[1]);
                    urls.Add(tokens[0]);
                }
            }
            listBox1.DataSource = data;
            listBox1.Tag = urls;
        }

在获取行的方法中:listBox1.DataSource = data; 它跳跃并做这个事件:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (listBox1.SelectedItem != null)
            {
                label4.Text = listBox1.SelectedItem.ToString();
                string startTag = "Url: ";
                string endTag = " ---";
                int startTagWidth = startTag.Length;
                int endTagWidth = endTag.Length;
                int index = 0;
                index = label4.Text.IndexOf(startTag, index);
                int start = index + startTagWidth;
                index = label4.Text.IndexOf(endTag, start + 1);
                string g = label4.Text.Substring(start, index - start);
                label4.Text = g;
                mainUrl = g;
            }
        }

最后我看到数据和listBox1.DataSource都包含9个项目。

毕竟这个程序正在运行。 我在listBox的右边看到了键和关键字的项目。 一旦我点击listBox1中的一个键,我就会在行上获得异常:

if (listBox1.SelectedItem != null)

在listBox1_SelectedIndexChanged事件中。

例外是:

指数数组的边界之外

System.IndexOutOfRangeException was unhandled
  HResult=-2146233080
  Message=Index was outside the bounds of the array.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.ListBox.ItemArray.GetItem(Int32 virtualIndex, Int32 stateMask)
       at System.Windows.Forms.ListBox.get_SelectedItem()
       at GatherLinks.Form1.listBox1_SelectedIndexChanged(Object sender, EventArgs e) in d:\C-Sharp\GatherLinks\GatherLinks-2\GatherLinks\GatherLinks\Form1.cs:line 543
       at System.Windows.Forms.ListBox.OnSelectedIndexChanged(EventArgs e)
       at System.Windows.Forms.ListBox.WmReflectCommand(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.WmCommand(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.WmKillFocus(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: 

我知道异常是什么意思但是我得到了什么以及如何解决它?

例如,如果我在使用键向上和向下运行程序时首先移动列表框中的键之间的移动,然后我点击其中一个我没有得到任何异常。 当我运行程序时会出现异常,然后立即用鼠标点击listBox中的一个键。

在它们之间移动然后点击它们中的一个是可以的,但是点击其中一个首先是例外。

编辑**

我现在看到它在进入listBox1_SelectedIndexChanged事件之前istBox1鼠标按下:

private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (Control.ModifierKeys == Keys.Control || ( Control.ModifierKeys == Keys.Control || e.Button == MouseButtons.Left))
            {
                listBox1.SelectionMode = SelectionMode.MultiExtended;
            }
            else if (e.Button == MouseButtons.Left)
            {
                listBox1.SelectionMode = SelectionMode.One;
            }
        }

这样做:

listBox1.SelectionMode = SelectionMode.MultiExtended;

然后回到selectedindexchanged事件并在行上抛出异常:

if (listBox1.SelectedItem != null)

这也是行号:543

这是反编译代码,在这种情况下, stateMask是标识所选项的状态掩码。

public object GetItem(int virtualIndex, int stateMask)
{
  int actualIndex = this.GetActualIndex(virtualIndex, stateMask);
  if (actualIndex == -1)
    throw new IndexOutOfRangeException();
  else
    return this.entries[actualIndex].item;
}

所以必须改变一些东西,因为正如Sriram指出的那样,在SelectedItem属性中有以下检查:

public object SelectedItem
{
  get
  {
    if (this.SelectedItems.Count > 0)
      return this.SelectedItems[0];
    else
      return (object) null;
  }
}

所以它以某种方式使它过去,然后在GetItem上失败。 我怀疑有一些线索傻瓜。

你不能这样做:

private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
  if (Control.ModifierKeys == Keys.Control || ( Control.ModifierKeys == Keys.Control || e.Button == MouseButtons.Left))
  {
    listBox1.SelectionMode = SelectionMode.MultiExtended;
  }
  else if (e.Button == MouseButtons.Left)
  {
    listBox1.SelectionMode = SelectionMode.One;
  }
}

我认为,在MouseDown事件中更改该属性会破坏窗口并再次重新创建它,这会搞乱在SelectedIndexChanged事件期间触发的内部信息。

只需注释掉该代码,并在设计时决定ListBox控件应该具有哪个SelectionMode。

您还应该确保获得正确的索引值,例如:

index = label4.Text.IndexOf(endTag, start + 1);
if (index > -1) {
  string g = label4.Text.Substring(start, index - start);
  label4.Text = g;
}

好的,我已经对此进行了一些调查,并且可以得出结论,问题可能与你给我们的任何代码有关,而不是其他的。 我不认为多线程正在进行的建议,因为WinForm中的多线程是非法的,并导致不同的异常。

你需要做什么user2760148为我们提供了一个小而完整的例子 创建一个新项目并使用相同的结果实现尽可能少的代码。

您的第一步是硬编码列表框的数据,只需拥有该mouseDown事件处理程序。 然后慢慢添加代码,直到找到问题为止。 你有可能自己找到问题......至少你会找到导致问题的步骤。 目前在这个例子中有太多“噪音”让我们很容易找到具体问题。

暂无
暂无

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

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