System.TypeInitializationException:

时间:2019-04-24 12:55:48

标签: c# sql .net

我想寻求帮助,因为我被困在探索问题上。 如果我在理解和寻求帮助方面犯了一个重大错误,那么我是一名初学者。

我开始编写程序,在其中创建了用于SQL查询和连接的静态类。登录后,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);
                }
            }
        }

    }
}

2 个答案:

答案 0 :(得分:1)

当静态构造函数中有未处理的异常时,就会发生该异常。

我猜您是在实例化ConnectionString之前尝试访问SQLConnection connection的{​​{1}}属性。

代替

connection

尝试

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

答案 1 :(得分:0)

非常感谢!以这种形式进行管理:

 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;
        }  
    }