0

I was having an exception.

I created a try catch for the InitializeComponent() like this.

try
{
    InitializeComponent();
    Auto_Complete();
}
catch(Exception ex)
{
    System.Windows.Forms.MessageBox.Show(ex.Message);
}

Then i get an exception saying "Object reference not set to an instance of an object.".

I was looking for the cause of the error.

Then i found that the error was due to a control i added in xaml.

xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
            <WindowsFormsHost Margin="272,10,396,42" Width="240">
                <wf:TextBox x:Name="txtAutoProductCode" AutoCompleteMode="SuggestAppend" AutoCompleteSource="CustomSource" />
            </WindowsFormsHost>

This is windows.forms control which i added into xaml for autocomplete capability.

But this exception is making it difficult.

i have created an autocomplete() function and connected the textbox:

    void Auto_Complete()
    {
        txtAutoProductCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        txtAutoProductCode.AutoCompleteSource = AutoCompleteSource.CustomSource;
        AutoCompleteStringCollection coll = new AutoCompleteStringCollection();

        SqlCeCommand com = new SqlCeCommand("SELECT ProductCode FROM Category_Master(CategoryName)", con);
        SqlCeDataReader dr;
        try
        {
            dr = com.ExecuteReader();
            while (dr.Read())
            {
                string aProduct = dr.GetString(0);
                coll.Add(aProduct);
            }
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message, System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        txtAutoProductCode.AutoCompleteCustomSource = coll;
    }

    public MainWindow()
    {
        try
        {
            InitializeComponent();
            Auto_Complete();
        }
        catch(Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString());
        }

    }

Here is the exception

        System.Windows.Markup.XamlParseException was unhandled
  HResult=-2146233087
  Message='Initialization of 'Billing.MainWindow' threw an exception.' Line number '6' and line position '9'.
  Source=PresentationFramework
  LineNumber=6
  LinePosition=9
  StackTrace:
       at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
       at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
       at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
       at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
       at System.Windows.Application.DoStartup()
       at System.Windows.Application.<.ctor>b__1(Object unused)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at Billing.App.Main() in c:\Users\kamalmohan\Documents\Visual Studio 2012\Projects\Billing\Billing\obj\Debug\App.g.cs:line 0
       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.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.InvalidOperationException
       HResult=-2146233079
       Message=Cannot have nested BeginInit calls on the same instance.
       Source=PresentationFramework
       StackTrace:
        at System.Windows.FrameworkElement.BeginInit()
        at MS.Internal.Xaml.Runtime.ClrObjectRuntime.InitializationGuard(XamlType xamlType, Object obj, Boolean begin)
       InnerException: 
14
  • are you sure it is due to the control and not due to something you are doing in Auto_Complete()? If you are sure.. u will need to check if you are doing something funny in the constructor of the control Commented Oct 28, 2013 at 7:48
  • 2
    Use ex.ToString() in your MessageBox.Show(). This will show the full stack trace. Strong suggestion: Don't catch exceptions around InitializeComponent(). That method should never throw exceptions and if it does, you're most certainly seeing a programming error and your form will not look like what it should. Commented Oct 28, 2013 at 7:48
  • Whats Auto_Complete() doing? Error might be occuring there? Its inside the try catch block. Commented Oct 28, 2013 at 7:48
  • 1
    I have edited the code from your comment into the question. When you are debugging this, what line does the exception happen on? we are not psychic. Posting the exception text and start of the stack trace would be incredibly useful... Commented Oct 28, 2013 at 8:31
  • 1
    Can you at least post the top of the stack trace? Commented Oct 28, 2013 at 8:32

1 Answer 1

1

This may well help solve it for you to work out exactly where the problem is

XAMLParseException is a common exception thrown in WPF. Unfortunately it isn't very helpful.

To help find out what the real error is, you can turn on exception reporting much earlier in Visual Studio. Default key combination is Ctrl + Alt + E. From there, check all the boxes.

Now the exception that is thrown in your code will be highlighted in the debugger.

https://stackoverflow.com/a/9045411/427684

Sign up to request clarification or add additional context in comments.

4 Comments

i have done that. I first got a NullReferenceException "Object reference not set to an instance of an object." Then i continued and got another TargetInnovationException "Exception has been thrown by the target of an invocation." Then another ReleaseHandleFailed "A SafeHandle or CriticalHandle of type 'System.Data.SqlServerCe.HashSafeHandle' failed to properly release the handle with value 0x01282598. contn..
..contn This usually indicates that the handle was released incorrectly via another means (such as extracting the handle using DangerousGetHandle and closing it directly or building another SafeHandle around it.)"
Can you establish what it is that has a null value? Don;t forget to check each part of a call e.g. thisCouldBeNull.thisCouldBeNull.thisCouldAlsoBeNull
Mark this as the answer if it led you to the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.