我在textBox上书写后出现System.AccessViolationException

时间:2018-11-10 11:33:28

标签: c#

我有一个代码可以从.txt文件中自动完成textBox的代码,当我在textBox中书写时,会显示此错误-> System.AccessViolationException:'试图读取或写入受保护的内存。这通常表明其他内存已损坏。'。我已经对其进行了研究,但仍然不知道为什么会这样。我需要一些帮助。

我的代码是:

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

namespace test
{
    public partial class Vender : UserControl
    {
        public Vender()
        {
            InitializeComponent();
        }

        string dirClientes = (Environment.CurrentDirectory + "/Bd/clientes.txt");
        string[] sugClientes = new string[File.ReadAllLines(Environment.CurrentDirectory + "/Bd/clientes.txt").Count()];

        private void textBoxCliente_TextChanged(object sender, EventArgs e)
        {   
            textBoxCliente.AutoCompleteSource = AutoCompleteSource.CustomSource;

            for (int i = 0; i < sugClientes.Length; i++)
            {
                textBoxCliente.AutoCompleteCustomSource.Add(sugClientes[i]);
            }
            textBoxCliente.AutoCompleteMode = AutoCompleteMode.Suggest;
        }

        private void LoadClientSuggestions()
        {
            string[] lines = File.ReadLines(dirClientes).ToArray();
            int nLine = File.ReadAllLines(dirClientes).Count();

            for (int j = 0; j < nLine; j++)
            {
                string[] parts = lines[j].Split(new char[] { '|' });
                sugClientes[j] = parts[1];
            }
        }

        private void textBoxCliente_Leave(object sender, EventArgs e)
        {
            int nLine = File.ReadAllLines(dirClientes).Count();
            int x = 0;
            string text = textBoxCliente.Text;


            for (int i = 0; i < nLine; i++)
            {
                if (text == sugClientes[i])
                    x = 1;
            }

            if (textBoxCliente.Text == "")
                ;
            else if (x == 0)
            {
                MessageBox.Show("Cliente não existente!", "Erro.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textBoxCliente.Clear();
            }
        }

        private void Vender_Load(object sender, EventArgs e)
        {
            dataGridViewProds.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            LoadClientSuggestions();
        }
    }
}

0 个答案:

没有答案