I am using an open file dialog which I dragged from the toolbox onto my form. The file dialog was working fine until recently.
I've searched high and low for an answer online but none of them work. I started the project on my home computer and then copied the whole project folder to my work computer so that I can work on it both at home and at work.
The file dialog works fine even now on my work computer but after I make changes to the code (at work) and copy the new project folder to my home computer the issue occurs. This is not managed in TFS or any other shared location. This is a private project that I am working on. The code where the issue occurs is as below:
Thread th;
private void btnUploadToDB_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.Title = "Select new data file";
openFileDialog1.Filter = "Excel Files |*.xlsx";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog1.FileName;
}
else if (DialogResult == DialogResult.None)
{
return;
}
th = new Thread(uploadToDB);
Control.CheckForIllegalCrossThreadCalls = false;
th.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
GC.Collect();
}
}
The stack trace when the error occurs is as below:
System.AccessViolationException was unhandled Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt. Source=System.Windows.Forms StackTrace: at System.Windows.Forms.FileDialogNative.IFileDialog.Show(IntPtr parent) at System.Windows.Forms.FileDialog.RunDialogVista(IntPtr hWndOwner) at System.Windows.Forms.FileDialog.RunDialog(IntPtr hWndOwner) at System.Windows.Forms.CommonDialog.ShowDialog(IWin32Window owner) at System.Windows.Forms.CommonDialog.ShowDialog() at Form1.Form1.btnUploadData_Click(Object sender, EventArgs e) in C:\Users\User1\Documents\Visual Studio 2010\Projects\C#_Projects\C# Projects\Solution 1\Solution 1\Form1.cs:line 458 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.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.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 System.Windows.Forms.Application.Run(Form mainForm) at Form1.Program.Main() in C:\Users\User1\Documents\Visual Studio 2010\Projects\C#_Projects\C# Projects\Solution 1\Solution 1\Program.cs:line 18 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:
Further, I tried creating an empty project on my home computer where the issue occurs and added an openfiledialog in the same manner and it works fine. The issue seems to be with only this application and that too when it is on my home machine.
I am adding the updateToDB method as requested. I have modified some values so there might be lines that don't make sense, however, I believe it is not relevant to the issue at hand.
private void uploadToDB()
{
try
{
string values = "";
string excelConString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" +
filePath + "'; Extended Properties='Excel 12.0 Xml;HDR=Yes;IMEX=1;'";
string excelSql = "select * from [Sheet1$]";
string accessConString = GlobalOleDBCommands.DBconString;
string accessSql = "delete from table1";
GlobalOleDBCommands.CommandExecuteNonQuery(accessSql, accessConString);
using (OleDbDataAdapter adap = new OleDbDataAdapter(excelSql, excelConString))
{
using (DataTable dt = new DataTable())
{
adap.Fill(dt);
using (OleDbConnection accessCon = new OleDbConnection(accessConString))
{
accessCon.Open();
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
for (int j = 0; j <= dt.Columns.Count - 1; j++)
{
values = values.Trim() + dt.Rows[i][j] + ",";
}
values = Strings.Left(values, (Strings.Len(values) - 1));
string value1 = SplitAndReturnText(values, ",", 0);
string value2 = SplitAndReturnText(values, ",", 1);
string value3 = SplitAndReturnText(values, ",", 2);
string value4 = SplitAndReturnText(values, ",", 3);
accessSql = "insert into table1 (value1,value2,value3,value4) values(@value1,@value2,@value3,@value4)";
using (OleDbCommand dtToAccessCmd = new OleDbCommand(accessSql, accessCon))
{
dtToAccessCmd.Parameters.AddWithValue("@value1", value1);
dtToAccessCmd.Parameters.AddWithValue("@value2", value2);
dtToAccessCmd.Parameters.AddWithValue("@value3", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(value3.ToLower()));
dtToAccessCmd.Parameters.AddWithValue("@value4", value4);
try
{
dtToAccessCmd.ExecuteNonQuery();
}
catch (Exception)
{
}
this.lblProgress.Text = (i + "/" + ((dt.Rows.Count) - 1)).ToString();
this.lblProgress.Refresh();
}
// Reset value variable to null.
values = "";
}
}
}
}
accessSql = "select max(end_time) from table1 where user_name='" +
Environment.UserName + "'";
DateTime start_time = Convert.ToDateTime(GlobalOleDBCommands.
CommandExecuteScalar(accessSql, GlobalOleDBCommands.DBconString));
DateTime end_time = DateTime.Now;
double total_time = (end_time - start_time).TotalMinutes;
string fieldValues = "start_time, end_time, user_name, task_name, total_time,task_count";
accessSql = "insert into table1 (" + fieldValues + ") values ('" +
start_time + "','" + DateTime.Now + "','" + Environment.UserName +
"','Update to DB','" + total_time + "','1')";
GlobalOleDBCommands.CommandExecuteNonQuery(accessSql, GlobalOleDBCommands.DBconString);
MessageBox.Show("New data added ");
this.lblProgress.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Could someone please advise what is causing this issue as I am not able to work on changes to the code at home for the fear that it would not work when I transfer to my work machine.
uploadToDB
method too? – keenthinkeruploadToDB
method? If so, change the line in your codeControl.CheckForIllegalCrossThreadCalls = false;
toControl.CheckForIllegalCrossThreadCalls = true;
(or comment it out) to see if maybe you have a classic cross thread exception. Such problems can be solved easily (for example withControl.Invoke
or using the Task Parallel Library) . And generally do not turn standard framework protection mechanisms off (as long as it's not really needed and you know what you're doing). – keenthinker