首页 > 解决方案 > 尝试语句不执行 - 直接赶上

问题描述

我正在设置 a winform,它将学生的名字、姓氏和学生 ID 放入sql名为 的数据库college中,并执行一个搜索该学生的存储过程,然后在DataGridView按下搜索按钮时将结果显示在 a 中。每当我按下搜索按钮时,我都会收到以下错误

“在 Search2.exe 中发生了‘System.TypeInitializationException’类型的第一次机会异常”。

我的程序正在跳过Try显示的块,并进入Catch语句。谁能告诉我这是为什么?

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

namespace Search2
{
    public partial class frmSearch : Form
    {
        public frmSearch()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string studid, fname, lname;

            try
            {
                // get the values
                fname = txtFname.Text.Trim();
                lname = TxtLname.Text.Trim();
                studid = txtStudentID.Text.Trim();

                //instantiate datatier
                Class1 astudent = new Class1();
                DataSet ds = new DataSet();

                ds = astudent.GetStudents(studid, fname, lname);

                // populate the datagrid with dataset
                dgvStudents.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {

            }
        }

        private void frmSearch_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'collegeDataSet.STUDENT' table. You can move, or remove it, as needed.
            //this.sTUDENTTableAdapter.Fill(this.collegeDataSet.STUDENT);

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Data.SqlClient;
using System.Globalization;

namespace Search2
{
    class Class1: frmSearch
    {
        static String connString = ConfigurationManager.ConnectionStrings["Data Source=EVEDELL17;Initial Catalog=College;Integrated Security=True"].ConnectionString;
        static SqlConnection myConn = new SqlConnection(connString);
        static System.Data.SqlClient.SqlCommand cmdString = new System.Data.SqlClient.SqlCommand();

        public DataSet GetStudents(string studid, string fname, string lname)
        {
            try
            {
                // Open Connection
                myConn.Open();
                //clear command argument
                cmdString.Parameters.Clear();
                //command
                cmdString.Connection = myConn;
                cmdString.CommandType = CommandType.StoredProcedure;
                cmdString.CommandTimeout = 1500;
                cmdString.CommandText = "SearchStudent";
                // define input parameter

                cmdString.Parameters.Add("@fname", SqlDbType.VarChar, 1).Value = fname;
                cmdString.Parameters.Add("@lname", SqlDbType.VarChar, 25).Value = lname;
                // adapter and daraset
                SqlDataAdapter aAdapter = new SqlDataAdapter();
                aAdapter.SelectCommand = cmdString;
                DataSet aDataSet = new DataSet();
                // fill adapter
                aAdapter.Fill(aDataSet);
                //return Dataset
                return aDataSet;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
            finally
            {
                myConn.Close();
            }
        }
    }
}

标签: c#winformsexceptiontry-catch

解决方案


从异常类型来看TypeInitializationException——我怀疑问题出在静态字段初始化器上:

static String connString = ConfigurationManager.ConnectionStrings["Data Source=EVEDELL17;Initial Catalog=College;Integrated Security=True"].ConnectionString;
static SqlConnection myConn = new SqlConnection(connString);
static System.Data.SqlClient.SqlCommand cmdString = new System.Data.SqlClient.SqlCommand();

这些初始化程序将在它们的包含类 ( ) 第一次Class1被运行时“触及”时运行。因为它们不在方法中,所以当它们失败时编译器很难提供有用的堆栈跟踪。尝试用静态构造函数替换内联初始化器:

static String connString;
static SqlConnection myConn;
static System.Data.SqlClient.SqlCommand cmdString;

static Class1() {
    connString = ConfigurationManager.ConnectionStrings["Data Source=EVEDELL17;Initial Catalog=College;Integrated Security=True"].ConnectionString;
    myConn = new SqlConnection(connString);
    cmdString = new System.Data.SqlClient.SqlCommand();
}

我认为这样你会得到更好的错误信息。您还可以在构造函数中设置断点以准确查看初始化期间发生的情况。

在此处阅读更多信息:https ://docs.microsoft.com/en-us/dotnet/api/system.typeinitializationexception?view=netframework-4.8#Static


推荐阅读