C# Error "The type initializer for ... threw an exception
Asked Answered
U

12

38

This error occurs only in some computers. By reading the stack information, there is some problem when I call to this static method ("FormatQuery") in a static class:

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlexCel.Report;
using FlexCel.XlsAdapter;
using ComboBox=System.Windows.Forms.ComboBox;

namespace XSoftArt.A
{
    static class RHelper
    {
        private static string FormatQuery(string FieldName, int Count,
            CheckedListBox chekedListBox)
        {
            string ID = string.Empty;
            int n = Count;

            foreach (DataRowView item in chekedListBox.CheckedItems)
            {
                ID = ID + item["" + FieldName + ""];
                if (n > 1)
                {
                    ID = ID + " , ";
                    n--;
                }
            }
            return ID;
        }

        public static string FormatQuery(CheckedListBox chekedListBox)
        {
            return FormatQuery(chekedListBox.ValueMember,
                chekedListBox.CheckedItems.Count, chekedListBox);
        }
    }

So, what's the problem? How do I solve it? Is there something wrong with the project configuration or debbuging mode or what?

Error information:

   at XSoftArt.EVS.ReportHelper.FormatQuery(CheckedListBox chekedListBox)
   at XSoftArt.EVS.NewEmailSelectClient.LoadList_v2(String search, TextBox txtbox)
   at XSoftArt.EVS.NewEmailSelectClient.LoadContacts()
   at XSoftArt.EVS.NewEmailSelectClient.button7_Click(Object sender, EventArgs e)
   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.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Uterus answered 4/8, 2009 at 7:54 Comment(10)
Does it say which exception it threw?Workout
And since this class does not have a static initializer, are you sure it's this class?Workout
Check InnerException and detailsHeiner
A complete text for the exception description would be more helpfulRelativity
Could you please post the stack trace?Canaveral
and which FormatQuery?Heiner
I posted error information in question...Uterus
There's no mention of FormatQuery in that stack trace, are you sure it's this class that is the problem? Is this class complete in the question or did you leave something out?Workout
Sorry. I edited one more time my post and pasted error information again.Uterus
Are you missing a referenced DLL on the machines that it is failing on?Marchelle
M
4

I tried your code:

CheckedListBox cb = new CheckedListBox();
for (var i = 1; i < 11; i++)
  cb.Items.Add("Item " + i, i % 3 == 0);

string fmt = RHelper.FormatQuery(cb);
Console.WriteLine(fmt);
Console.ReadLine();

It threw an exception at this line:

foreach (DataRowView item in chekedListBox.CheckedItems)

// Unable to cast object of type 'System.String' to type 'System.Data.DataRowView'.

Maybe you are also facing the same kind of problem. Instead of casting to DataRowView, try making the following changes:

foreach (var item in chekedListBox.CheckedItems)
{
    ID = ID + item.ToString(); // item["" + FieldName + ""];

Because items in CheckedListBox are of object type.

Mileage answered 4/8, 2009 at 8:16 Comment(1)
I dont think so, because this code worked well in another project. I think this may be some other problems (I Copied this module from another project to this...). The cal to this method look like this(when I put arguments for SQL):"@StateID", ReportHelper.FormatQuery(db_InvoiceStateID). db_InvoiceStateID here is a checkedListBox component.Uterus
U
64

A Type Initializer exception indicates that the type couldn't be created. This would occur typically right before your call to your method when you simply reference that class.

Is the code you have here the complete text of your type? I would be looking for something like an assignment to fail. I see this a lot with getting app settings and things of that nature.

static class RHelper
{
     //If this line of code failed, you'd get this error
     static string mySetting = Settings.MySetting;
} 

You can also see this with static constructors for types.

In any case, is there any more to this class?

Ultimatum answered 29/10, 2009 at 17:29 Comment(2)
This is exactly the problem I had - valuing the static members doesn't happen until after the constructor is invoked. Thanks!Wolford
Genius answer... this was exactly my problem as well. I found it very hard to debug this as the exception was masking the real error. Thanks for your help.Tallow
A
8

I had the same error but in my case it was caused by mismatch in platform target settings. One library was set specifically to x86 while the main application was set to 'Any'...and then I moved my development to an x64 laptop.

Antechoir answered 29/10, 2012 at 12:56 Comment(0)
F
8

This problem can occur if a class tries to get value of a non-existent key in web.config.

For example, the class has a static variable ClientID

private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();

but the web.config doesn't contain the 'GoogleCalendarApplicationClientID' key, then the error will be thrown on any static function call or any class instance creation

Fusilier answered 1/3, 2013 at 6:34 Comment(0)
T
5

I got this error when I modified an Nlog configuration file and didn't format the XML correctly.

Thiel answered 21/8, 2012 at 17:1 Comment(0)
M
4

I tried your code:

CheckedListBox cb = new CheckedListBox();
for (var i = 1; i < 11; i++)
  cb.Items.Add("Item " + i, i % 3 == 0);

string fmt = RHelper.FormatQuery(cb);
Console.WriteLine(fmt);
Console.ReadLine();

It threw an exception at this line:

foreach (DataRowView item in chekedListBox.CheckedItems)

// Unable to cast object of type 'System.String' to type 'System.Data.DataRowView'.

Maybe you are also facing the same kind of problem. Instead of casting to DataRowView, try making the following changes:

foreach (var item in chekedListBox.CheckedItems)
{
    ID = ID + item.ToString(); // item["" + FieldName + ""];

Because items in CheckedListBox are of object type.

Mileage answered 4/8, 2009 at 8:16 Comment(1)
I dont think so, because this code worked well in another project. I think this may be some other problems (I Copied this module from another project to this...). The cal to this method look like this(when I put arguments for SQL):"@StateID", ReportHelper.FormatQuery(db_InvoiceStateID). db_InvoiceStateID here is a checkedListBox component.Uterus
U
1

If you have web services, check your URL pointing to the service. I had a simular issue which was fixed when I changed my web service URL.

Unblessed answered 2/2, 2010 at 15:44 Comment(0)
A
1

I got this error with my own code. My problem was that I had duplicate keys in the config file.

Aurea answered 31/8, 2011 at 17:35 Comment(0)
K
1

I got this error when trying to log to an NLog target that no longer existed.

Kaleb answered 11/6, 2012 at 21:36 Comment(0)
B
1

This can be caused by not having administrator permissions for Oracle Client. Add this in App.config file:

<IPermission class="Oracle.DataAccess.Client.OraclePermission,
 Oracle.DataAccess, Version=2.111.7.20, Culture=neutral,
 PublicKeyToken=89b483f429c47342" version= "1" Unrestricted="true"/>
Browbeat answered 9/4, 2015 at 19:20 Comment(0)
E
0

I had this problem and like Anderson Imes said it had to do with app settings. My problem was the scope of one of my settings was set to "User" when it should have been "Application".

Eisenberg answered 20/7, 2012 at 16:22 Comment(1)
And so where did you go to change this? Details, man, details!Tirado
T
0

I got this error when i had tried to use AWSSDK library to read ec2 instance value on load of application but the library dlls were missed in the deployed path.

Transcalent answered 7/3, 2023 at 11:19 Comment(0)
K
-4

This error was generated for me by having an incorrectly formatted NLog.config file.

Ketonuria answered 12/2, 2014 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.