使用数据库时表单因错误而关闭

Form closes with an error when working with the database

我试图做到这一点,以便在更改 comboBox 中的值时,数据库显示在 dataGridview 中。一切似乎都正常,但是当您关闭表单时会出现错误: 输入图片:

代码:

namespace Cursach
{
    public partial class VoucherForm : Form
    {
        public VoucherForm()
        {
            InitializeComponent();
        }

        public void VoucherCountry()
        {
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.AllowUserToOrderColumns = false;
            dataGridView1.AllowUserToResizeRows = false;
            dataGridView1.AllowDrop = false;
            dataGridView1.ReadOnly = true;

            DB dB = new DB();
            SqlCommand command = new SqlCommand("SELECT * FROM Voucher WHERE Name_Country= @nC", dB.ConnectionSQL());
            command.Parameters.Add("@nC", SqlDbType.VarChar).Value = comboBox1.SelectedValue;
            DataTable table = new DataTable();
            SqlDataAdapter adapter = new SqlDataAdapter();

            dB.OpenSQL();
            adapter.SelectCommand = command;
            adapter.Fill(table);
            dataGridView1.DataSource = table;
            dB.ClodeSQL();
        }


        private void VoucherForm_Load(object sender, EventArgs e)
        {
            this.countryTableAdapter.Fill(this.cursacDat.Country);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            VoucherCountry();
        }
}

您有一个 DB class,这有助于将您的数据库代码与您的用户界面代码分开。我将用于检索国家/地区数据的数据库代码移至 DB class。请注意 DB class 如何对用户界面一无所知,而用户界面对数据库一无所知。

需要关闭和释放数据库对象。 using 块会为您处理此问题,即使出现错误也是如此。

    public class DB
    {
        private string ConStr = "Your connection string";

        public DataTable GetCountryData(string nC)
        {
            DataTable dt = new DataTable();
            using (SqlConnection cn = new SqlConnection(ConStr))
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Voucher WHERE Name_Country= @nC", cn))
            {
                cmd.Parameters.Add("@nC", SqlDbType.VarChar, 100).Value = nC;
                cn.Open();
                dt.Load(cmd.ExecuteReader());
            }
            return dt;
        }
    }

然后在表格中。

    private void OpCode()
    {
         if (comboBox1.SelectedIndex < 0)
         {
            MessageBox.Show("Please select a value in the drop down.");
            return;
         }
        DB DataClass = new DB();
        dataGridView1.DataSource = DataClass.GetCountryData(comboBox1.SelectedValue.ToString());
    }