winforms 我收到异常System.ArgumentOutOfRangeException

vfwfrxfs  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(424)

我有一个组合框,我想让它自动查找并建议一个短语与任何单词从字典。我发现这个解决方案-link,但我注意到,如果短语没有找到,那么应用程序可能会崩溃-无效参数值0是无效的索引。试图绕过这个在每一个可能的方式,但是最后应用程序完全关闭了。这个解决方案中有什么错误,有没有可能以某种方式修复它,如果没有找到短语,显示一个关于这个的消息框,例如。
词典中的短语与第一个问题中的短语相同:
门开启元件
外门
室内门
滑动门
应用程序并不总是崩溃,我认为这是由于在初始字典的组合框中输入了这些字母
我在写的时候被压垮了:
奥瑟
erot等。
然后点击窗体,
但是当我尝试搜索时什么也没发生:
abc公司
嘴等。
我无法修复代码,我希望你能。谢谢。

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

namespace WindowsFormsApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listOriginal.Add("Doors opening elements");
            listOriginal.Add("exterior doors");
            listOriginal.Add("interior doors");
            listOriginal.Add("sliding doors");

            this.comboBx.Items.AddRange(listOriginal.ToArray());
        }

        // Bind default keywords
        List<string> listOriginal = new List<string>();
        // save new keywords
        List<string> listNew = new List<string>();
        private void comboBx_TextUpdate(object sender, EventArgs e)
        {
            //clear combobox
            this.comboBx.Items.Clear();
            //clear listNew
            listNew.Clear();
            foreach (var item in listOriginal)
            {
                // call ToLower() .. not case sensitive
                if (item.ToLower().Contains(this.comboBx.Text))
                {
                    //add to ListNew
                    listNew.Add(item);
                }
            }
            this.comboBx.Items.AddRange(listNew.ToArray());
            this.comboBx.SelectionStart = this.comboBx.Text.Length;
            Cursor = Cursors.Default;
            // Automatically pop up drop-down
            this.comboBx.DroppedDown = true;
        }
    }
}

编译代码后在第15行得到异常:

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

namespace WindowsFormsApp
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());// <-------- this
        }
    }
}

堆栈追踪:

System.ArgumentOutOfRangeException
  HResult=0x80131502
  Message=InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index
  Source=System.Windows.Forms
  StackTrace:
   at System.Windows.Forms.ComboBox.ObjectCollection.get_Item(Int32 index)
   at System.Windows.Forms.ComboBox.get_Text()
   at System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
   at System.Windows.Forms.ComboBox.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.Form.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at WindowsFormsApp.Program.Main() in C:\Users\denis\source\repos\WindowsFormsApp\WindowsFormsApp\Program.cs:line 15
d6kp6zgx

d6kp6zgx1#

该异常意味着集合中没有项。在这种情况下,TextUpdate事件将清除ComboBox项,当您在ComboBox没有项的情况下单击该ComboBox时,将发生异常。
此问题的解决方法是在TextUpdate事件结束时保持填充ComboBox,并且仅在文本匹配时操作下拉列表。如果listOriginal包含更新的文本,则将newList添加到ComboBox并将ComboBox.DroppedDown设置为true。否则,将listOriginal添加到ComboBox并将ComboBox.DroppedDown设置为false。

private void comboBx_TextUpdate(object sender, EventArgs e)
    {
        //clear combobox
        this.comboBx.Items.Clear();
        //clear listNew
        listNew.Clear();

        foreach (var item in listOriginal)
        {
            // call ToLower() .. not case sensitive
            if (item.ToLower().Contains(this.comboBx.Text.ToString()))
            {
                //add to ListNew
                listNew.Add(item);
            }
        }

        this.comboBx.SelectionStart = this.comboBx.Text.Length;
        Cursor = Cursors.Default;

        // Check if ListNew has been populated.

        if (listNew.Count != 0)
        {

            this.comboBx.Items.AddRange(listNew.ToArray());
            // Automatically pop up drop-down
            this.comboBx.DroppedDown = true;

        }
        else
        {
            this.comboBx.Items.AddRange(listOriginal.ToArray());
            // Automatically close dropdown
            this.comboBx.DroppedDown = false;
            
        }
    }

肯定有更好的方法来修复这个错误,但我想这是最简单的修复方法。希望它有帮助!

相关问题