I'm getting this weird AccessViolationException in my C# program that uses a MySQL database connection. I use values from the database to generate an autocorrect facility for a textbox. Here's the code snippet:
private void textBoxName_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection asc = Database.getSuggestedNames(textBoxName.Text);
if (asc != null)
textBoxName.AutoCompleteCustomSource = asc;
}
The getSuggestedNames(string) method is implemented in Database.cs as follows:
public static AutoCompleteStringCollection getSuggestedNames(string namepart)
{
string query = "SELECT name FROM worker WHERE name LIKE '%"+namepart+"%';";
string[] namecolumn = { "name" };
List<string>[] names = getValues(query,namecolumn);
AutoCompleteStringCollection namec = new AutoCompleteStringCollection();
for (int i = 0; i < names[0].Count; i++)
namec.Add(names[0][i]);
return namec;
}
The actual query is done with a separate method in the same file called getValues:
private static List<string>[] getValues(string query,string[] columnNames)
{
if (connection == null)
initialize();
if (connection.State == ConnectionState.Closed)
connection.Open();
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
List<string>[] list = new List<string>[columnNames.Length];
for (int i = 0; i < columnNames.Length; i++)
list[i] = new List<string>();
while (dataReader.Read())
{
for(int i=0;i<columnNames.Length;i++)
list[i].Add(dataReader[columnNames[i]] + "");
}
dataReader.Close();
connection.Close();
return list;
}
The exception always occurs when the user enters data into the textbox textBoxName. The error is not very frequent and the call stack shows its the external code that causes the problem. So I assume it should be MySQL that causes the problem.
Can somebody please help me to overcome this problem since there is nothing I can do.
The exact line the error occurs on is line 17 in the following code,which is not much use for me for debugging. Visual Studio does not show any other place. The stack trace shows [external code]. But here it is anyway:
1 using System;
2 using System.Collections.Generic;
3 using System.Windows.Forms;
4
5 namespace LabourManagement
6 {
7 static class ManagementProgram
8 {
9 /// <summary>
10 /// The main entry point for the application.
11 /// </summary>
12 [STAThread]
13 static void Main()
14 {
15 Application.EnableVisualStyles();
16 Application.SetCompatibleTextRenderingDefault(false);
17 Application.Run(new General());
18
19 }
20 }
21 }