Trouble with a Folder Diaolg causing a nullReferenceExeption - please help!
-
Sunday, June 15, 2008 8:30 AM
Hi.
I am using a Folder dialog to uh... select a folder in Visual C# 2005 Express Edition.
It works fine most of the time.
However every now and then I get a nullReferenceExeption when I click the mouse on the dialog.
Sometimes it happens straight away. Sometimes it happens after many, many clicks.
I have no idea what is wrong! :(
Here is my code (with the trouble causing line in red):private void openToolStripMenuItem_Click(object sender, EventArgs e)
...and here is my exception detail...
{
timer1.Enabled = false;
folderBrowserDialog1.SelectedPath = lastDir;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string oldPath = label1.Text;
string errorMesage = "";
string path = "";
bool fileMissing = false;
label1.Text = System.Convert.ToString(folderBrowserDialog1.SelectedPath);
//Check for files
fileCheckPath[0] = @"\uisettings.ini";
fileCheckPath[1] = @"\custom.ini";
fileCheckPath[2] = @"\upper_screen.bmp";
fileCheckPath[3] = @"\lower_screen.bmp";
fileCheckPath[4] = @"\brightness.bmp";
fileCheckPath[5] = @"\btn2.bmp";
fileCheckPath[6] = @"\btn3.bmp";
fileCheckPath[7] = @"\btn4.bmp";
fileCheckPath[8] = @"\card_icon_blue.bmp";
fileCheckPath[9] = @"\folder_up.bmp";
fileCheckPath[10] = @"\menu_bg.bmp";
fileCheckPath[11] = @"\progress_bar.bmp";
fileCheckPath[12] = @"\progress_wnd.bmp";
fileCheckPath[13] = @"\spin_btn_left.bmp";
fileCheckPath[14] = @"\spin_btn_right.bmp";
fileCheckPath[15] = @"\title_bg.bmp";
fileCheckPath[16] = @"\title_left.bmp";
fileCheckPath[17] = @"\title_right.bmp";
fileCheckPath[18] = @"\calendar\clock_colon.bmp";
fileCheckPath[19] = @"\calendar\clock_numbers.bmp";
fileCheckPath[20] = @"\calendar\day_numbers.bmp";
fileCheckPath[21] = @"\calendar\year_numbers.bmp";
int i = 0;
for (i = 0; i <= 21; i++)
{
path = (@label1.Text + @fileCheckPath[i]);
if (File.Exists(path) != true)
{
errorMesage = errorMesage + @"
" + fileCheckPath[i];
fileMissing = true;
}
}
if (fileMissing == true)
{
MessageBox.Show(( @"Warning!
" + label1.Text + @"
is missing the following files...
" + errorMesage), "File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Text = "AK Edit - " + oldPath;
label1.Text = oldPath;
}
else
{
getConfig();
checkStartData();
getImages();
initColorButtons();
initColorPage();
initLayout();
refreshColBacks();
timer1.Enabled = true;
tabControl1.Visible = true;
saveToolStripMenuItem1.Enabled = true;
refreshToolStripMenuItem1.Enabled = true;
reloadImagesToolStripMenuItem.Enabled = true;
screensToolStripMenuItem.Enabled = true;
MicroSDToolStripMenuItem.Enabled = true;
directEditToolStripMenuItem.Enabled = true;
LimitToolStripMenuItem.Enabled = true;
toolStripButton2.Enabled = true;
toolStripButton3.Enabled = true;
toolStripButton4.Enabled = true;
toolStripButton5.Enabled = true;
toolStripButton6.Enabled = true;
lastDir = label1.Text;
writeIni();
}
}
}System.NullReferenceException was unhandled
Any help would be much appreciated - this is driving me nuts!
Message="Object reference not set to an instance of an object."
Source="System.Windows.Forms"
StackTrace:
at System.Windows.Forms.UnsafeNativeMethods.Shell32.SHBrowseForFolder(BROWSEINFO lpbi)
at System.Windows.Forms.FolderBrowserDialog.RunDialog(IntPtr hWndOwner)
at System.Windows.Forms.CommonDialog.ShowDialog(IWin32Window owner)
at WindowsApplication1.Form1.openToolStripMenuItem_Click(Object sender, EventArgs e) in D:\Documents\Visual Studio 2005\Projects\AceKardEditor.cs:line 1882
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(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(Int32 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 WindowsApplication1.Program.Main() in D:\Documents\Visual Studio 2005\Projects\AceKard Skin Editor\AceKard Skin Editor\Program.cs:line 17
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Thanks,
Dan.
- Moved by Peter RitchieMVP, Moderator Thursday, June 19, 2008 8:01 PM off-topic
All Replies
-
Sunday, June 15, 2008 9:14 AMIs "folderBrowserDialog1" set to an instance of a dialog object?
Try setting a breakpoint on the line and checking the variable contents.
http://presentationmode.blogspot.com/
Please remember to mark the replies as answers if they help and unmark them if they provide no help. -
Sunday, June 15, 2008 1:26 PMIt's your "lastDir". The stack trace shows you its failing in SHBrowseForFolder(), which means you have a valid dialog object. You just don't have it configured properly.
Put in a try/catch block and set a break point in the catch. When your code throws the intermittent error, you will be able to examine "lastDir" which I expect will be invalid.
I think it will be null, but there are other non-null values that should also throw and error, although a different error.
<edit>
On second thought, lastDir may not be null. But I would still expect it to be invalid for some reason. Maybe the directory has been deleted or gone offline. Or maybe you dialog's "RootFolder" value has a problem. I give these suggestions because you say this is happening intermittently.
I consider the best suggestion to be to wrap with a try/catch block and set a breakpoint in the catch() block and see what you can learn from the state of the FolderBrowserDialog at the point of failure..- Edited by xalnix Sunday, June 15, 2008 1:58 PM A little rethought
-
Sunday, June 15, 2008 5:10 PMHi.
Thanks for the suggestions.
The "lastDir" and "RootFolder" values seem to be fine.
What should I be looking for in the break point?
(I am very new to this so please treat me like an idiot!)
Thanks,
Dan.
-
Monday, June 16, 2008 5:48 AMOK...
So I rolled back to a previous version of my program to see what might be causing this error.
I started to add in the three or four new elements that had changed in the last revision.
It appears that having a tool strip makes my folder dialog mysteriously start throwing out null exceptions.
Now...
I'd quite like my tool strip, so does anyone have any ideas as to why the tool strip might affect the folder select dialog?
Most bizarre...
?
-
Monday, June 16, 2008 5:59 AMmay you can set a break points to see which object is null, then you can know why
MSN:h2zy@hotmail.com -
Monday, June 16, 2008 9:47 AM
I notice that your folderBrowserDialog1 is a field in your class. I would try declaring it within your openToolStripMenuItem_Click method instead. This will ensure it gets properly initialised each time the event handler is called.
-
Monday, June 16, 2008 12:37 PMHere comes a leftfield suggestion. :)
How is your program's Main() function defined?
Is it:
[STAThread]
static void Main(...
Or:
[MTAThread]
static void Main(...
I've had weird problems with folder browsers with MTAThread in the past.
-
Monday, June 16, 2008 1:09 PM
DT1000,
Matthew may be on to something. FolderBrowserDialog() calls SHBrowseForFolder(). The documentation for SHBrowseForFolder() warns about Multi-threaded COM. Since you have no control over how FolderBrowserDialog calls SHBrowseForFolder(), using the [STAThread] instead of [MTAThread] sounds like a best practice.
Does anyone know what the default is when not otherwise specified (STA or MTA)?
As for the Break Point, in your exception handler where you set the break point, examine the values of FolderBrowserDialog1.SelectedPath, and FolderBrowserDialog1.RootFolder. If they both look like like valid strings for directories, then look at your system and make sure the directories exist.The main thing is to collect additional diagnostic information at the point of failure, i.e., in the catch() block.
Read the documentation on SHBrowseForFolder() and the BROWSEINFO structure. Your call to FolderBrowseDialog() has to be mapped to this call by the framework, so understanding the lower level function may shed more light on solving the problem.
-
Tuesday, June 17, 2008 2:13 PMThanks for your help, everyone.
I checked my Main() function and, alas, it is already [STAThread].
I also tried declaring my folderBrowserDialog too:
FolderBrowserDialog
selectDir = new FolderBrowserDialog();
selectDir.Description = "Please select the folder that contains your uisettings.ini file.";
selectDir.SelectedPath = lastDir;
selectDir.ShowNewFolderButton = false;
DialogResult result = new DialogResult();
result = selectDir.ShowDialog();
...I still get the same problem as soon as I add a tool strip.
Any other suggestions - this is beginning to wind me up! :(
Thanks for all your help so far!
Cheers,
Dan. -
Tuesday, June 17, 2008 5:23 PMI created a new app, dropped a ToolStrip on the form1. Then added the following code. This does not cause an exception. So, I wonder about your ToolStrip initialization.
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog f = new FolderBrowserDialog();
f.Description = "Description";
f.SelectedPath = "Program Files"; // on purpose, I chose something outside of my Documents and Settings folder
f.ShowNewFolderButton = false;
DialogResult r = f.ShowDialog();
} -
Wednesday, June 18, 2008 2:08 PMOK.
I thought I'd check this out with a new app too.
I did the folllowing:
1) Made a new app
2) Added a tool strip with 1 item
3) Copied & pasted your code above
4) Tested it - worked fine
5) Added a menu strip with one item linking to the same code
6) Tested it - same nullReferrenceException error!
Could this be anything to do with my version of Visual C# (2005 Express)?
Or maybe that I'm only using .NET 2.0?
And the maybe the fact that I am on Vista 64 might be throwing a spanner in? (It ususally does).
:(
Thanks once again for your help!
Dan. -
Wednesday, June 18, 2008 7:13 PM
I am not able to recreate the problem...
My tool strip did not have an item, so I added one with no code/event hander. Tests fine.
Added a menu strip. Test fine.
Added an item to the menu strip and an event handler for the click event on the item. Tests fine.
Referenced the same event handler for the tool strip item click event. Tests fine.
Furthermore, I copied the same code to the toolstrip/menustrip item's event handler. Tests fine.
I doubt it's C# 2005 Express. I tried with C# 2005.
I doubt its .NET 2.0. I tried with .NET 2.0.
It could be Vista 64 (try your app on something else, mine runs on XP SP2). Do you have the VS SPs installed?
When you started this thread the problem was intermittent. Now it sounds like you have a way to make it fail every time. Is that true?
Here's my entire Form1.cs code...namespace ToolStripPOC { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void toolStripButton1_Click(object sender, EventArgs e) { //MessageBox.Show("ToolTipButton Pressed"); FolderBrowserDialog f = new FolderBrowserDialog(); f.Description = "Description"; f.SelectedPath = "Program Files"; // on purpose, I chose something outside of my Documents and Settings folder f.ShowNewFolderButton = false; DialogResult r = f.ShowDialog(); } private void button1_Click(object sender, EventArgs e) { FolderBrowserDialog f = new FolderBrowserDialog(); f.Description = "Description"; f.SelectedPath = "Program Files"; // on purpose, I chose something outside of my Documents and Settings folder f.ShowNewFolderButton = false; DialogResult r = f.ShowDialog(); } } }
namespace ToolStripPOC { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.button1 = new System.Windows.Forms.Button(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.oneItemToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip1.SuspendLayout(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton1}); this.toolStrip1.Location = new System.Drawing.Point(0, 24); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(292, 25); this.toolStrip1.TabIndex = 0; this.toolStrip1.Text = "toolStrip1"; // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 22); this.toolStripButton1.Text = "toolStripButton1"; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // button1 // this.button1.Location = new System.Drawing.Point(24, 115); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(87, 39); this.button1.TabIndex = 1; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.oneItemToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(292, 24); this.menuStrip1.TabIndex = 2; this.menuStrip1.Text = "menuStrip1"; // // oneItemToolStripMenuItem // this.oneItemToolStripMenuItem.Name = "oneItemToolStripMenuItem"; this.oneItemToolStripMenuItem.Size = new System.Drawing.Size(61, 20); this.oneItemToolStripMenuItem.Text = "OneItem"; this.oneItemToolStripMenuItem.Click += new System.EventHandler(this.toolStripButton1_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 266); this.Controls.Add(this.button1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.menuStrip1); thisthis.MainMenuStrip = this.menuStrip1; this.Name = "Form1"; this.Text = "Form1"; this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.Button button1; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem oneItemToolStripMenuItem; } } -
Thursday, June 19, 2008 8:01 PMModerator
For questions and discussions regarding client application development using Windows Forms controls and features, please see http://forums.microsoft.com/msdn/ShowForum.aspx?ForumID=8&SiteID=1
http://www.peterRitchie.com/blog- Marked As Answer by Ed Price - MSFTMicrosoft Employee, Moderator Friday, May 11, 2012 4:06 AM
Friday, May 11, 2012 4:07 AMModerator
This thread was moved into the Off Topic forum. I can move it into a specific forum for you if you want.
Thanks!
Ed Price (a.k.a User Ed), SQL Server Experience Program Manager (Blog, Twitter, Wiki)
- Proposed As Answer by Ed Price - MSFTMicrosoft Employee, Moderator Friday, May 11, 2012 4:07 AM
- Marked As Answer by Ed Price - MSFTMicrosoft Employee, Moderator Friday, May 11, 2012 4:07 AM