You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio开发Access应用:窗口启动后立即关闭问题求助

问题分析与修复方案

核心问题:窗体构造函数的递归调用

你的代码里最大的问题是在Form1的构造函数中调用了Application.Run(new Form1()),这会导致无限递归创建Form1实例,程序启动后会因栈溢出或资源耗尽直接崩溃,窗体根本无法正常显示。

具体修改步骤

1. 修正程序入口逻辑

WinForms程序的启动逻辑应放在Program.cs的Main方法中,而非窗体构造函数。创建或修改Program.cs如下:

using System;
using System.Windows.Forms;

namespace App_For_Test_Base
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

2. 清理Form1构造函数

移除构造函数中多余的启动代码,仅保留组件初始化调用:

public Form1()
{
    InitializeComponent();
}

3. 优化数据库操作代码

原代码用ExecuteNonQuery()执行SELECT语句是错误的(该方法适用于增删改操作),同时建议用using语句自动管理数据库资源,避免手动释放遗漏:

private void Form1_Load(object sender, EventArgs e)
{
    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Delphi-Projects\\UP.01.01.Khuraskin\\Project\\Test_Base.mdb;";
    
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        connection.Open();
        string query = "SELECT * FROM Teacher";
        
        using (OleDbCommand command = new OleDbCommand(query, connection))
        {
            using (OleDbDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    // 防止字段为NULL时抛出异常
                    listBox1.Items.Add(reader.IsDBNull(0) ? string.Empty : reader.GetString(0));
                }
            }
        }
    }
}

额外注意事项

  • 确保项目已引用System.Windows.Forms和System.Data程序集
  • 确认目标机器安装了Microsoft Access Database Engine 2010 Redistributable(对应ACE.OLEDB.12.0驱动)
  • 核对数据库文件路径,避免因路径错误导致连接失败

内容的提问来源于stack exchange,提问作者Horoshiy Plohoi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 04:20:17