简体   繁体   English

System.TypeInitializationException:

[英]System.TypeInitializationException:

I would like to ask for help because I got stuck in exploring the problem.我想寻求帮助,因为我陷入了探索问题的困境。 I'm a beginner developer if I made a big mistake of understanding and asking for your help :)如果我在理解和寻求您的帮助方面犯了一个大错误,我是一个初学者开发人员:)

I started writing a program where I created a static class for sql queries and connection.我开始编写一个程序,在其中我为 sql 查询和连接创建了一个静态类。 After logging in, the dgv should display the data:登录后,dgv 应显示数据:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;

namespace ParkingMaster
{
    static class SqlHandle
    {
        static SqlConnection connection;
        static SqlCommand command;

       static SqlHandle ()
        {
            connection.ConnectionString = ConfigurationManager.ConnectionStrings["ParkingMaster.Properties.Settings.Setting"].ToString();

            try
            {
                connection.Open();
                MessageBox.Show("Connection opened!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }  
        }

        public static void ConnClose()
        {
            try
            {
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "Hiba a kapcsolat bezárásakor");
                throw;
            }
        }

        public static List<Cars> ReadList()
        {
            List<Cars> results = new List<Cars>();

            try
            {
                string sql = "SELECT * FROM [Cars]";
                command = new SqlCommand(sql, connection);
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    results.Add(new Cars(
                        (int)reader["car_id"],
                        reader["car_plate_id_char"].ToString(),
                       (int)reader["car_plate_id_num"],
                       (DateTime)reader["creationdate"]));
                }
                reader.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
            return results;
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ParkingMaster
{
    class Cars
    {
        public int Id { get; set; }
        public string Plate_id_char { get; set; }
        public int Plate_id_num { get; set; }
        public DateTime Creationdate { get; set; }

        /*    
        public string FullInfo
        {
            get
            {
                return $"{id} {plate_id_char} {plate_id_num} {creationdate}";
            }
        }
        */

        public Cars(int id, string plate_id_char, int plate_id_num, DateTime creationdate)
        {
            this.Id = id;
            this.Plate_id_char = plate_id_char;
            this.Plate_id_num = plate_id_num;
            this.Creationdate = creationdate;
        }



    }
}


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;


namespace ParkingMaster
{
    public partial class mainForm : Form
    {
        List<Cars> cars;
        List<Cars> keresett_cars;
        //DbConnection dbConnection = new DbConnection();


        public mainForm()
        {
            InitializeComponent();
            //carFoundListbox.DataSource = cars;
        }

        private void mainForm_Load(object sender, EventArgs e)
        {
            try
            {
                cars = SqlHandle.ReadList();
                datagridview_megjelenit();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Hiba", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }

        private void btnVehicleListDgv_Click(object sender, EventArgs e)
        {

        }

        void datagridview_megjelenit()
        {
            //Inicializálás
            dataGridView1.DataSource = null;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.Rows.Clear();

            if (dataGridView1.Columns.Count == 0)
            {
                foreach (PropertyInfo elem in typeof(Cars).GetProperties())
                {
                    dataGridView1.Columns.Add(elem.Name, elem.Name);
                }
            }
            foreach (Cars item in cars) //sorok
            {
                dataGridView1.Rows.Add(); //sorokon belül az oszlopok (mezők) hozzáadása
                for (int i = 0; i < typeof(Cars).GetProperties().Length; i++)
                {
                    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[i].Value = typeof(Cars).GetProperties()[i].GetValue(item);
                }
            }
        }

    }
}

That exception occurs when there is an unhandled exception in a static constructor.当静态构造函数中存在未处理的异常时,就会发生该异常。

In your case, I am guessing, you are trying to access the ConnectionString property of the SQLConnection connection before you have instantiated connection .在您的情况下,我猜您正在尝试在实例化connection之前访问SQLConnection connectionConnectionString属性。

Instead of代替

connection.ConnectionString = ConfigurationManager.ConnectionStrings["ParkingMaster.Properties.Settings.Setting"].ToString();

try尝试

SQLConnection connection = new SQLConnection(ConfigurationManager.ConnectionStrings["ParkingMaster.Properties.Settings.Setting"].ToString());

Thank you very much!非常感谢! Managed in this form:以这种形式管理:

 static SqlHandle ()
    {
        connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ParkingMaster.Properties.Settings.Setting"].ToString());

        try
        {
            connection.Open();
            MessageBox.Show("Connection opened!");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            throw;
        }  
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM