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

C# WinForm简单CRUD开发报错:ConnectionString属性未初始化

Fixing "The ConnectionString property has not been initialized" in C# WinForms CRUD

Hey there, I’ve run into this exact issue a few times when setting up database connections in WinForms—let’s get this sorted out for you!

First, let’s break down why this error happens: your code is trying to use a database connection, but it hasn’t successfully loaded the connection string from your App.config file yet. Here’s how to fix it step by step:

1. Add the required assembly reference

WinForms projects don’t include the System.Configuration assembly by default, which is essential for reading settings from App.config. To add it:

  • Right-click your project in Solution Explorer → Add → Reference
  • In the Reference Manager, find and check System.Configuration → Click OK

2. Correct your DBConnection class code

Your snippet cuts off, but the core issue is likely how you’re trying to fetch the connection string. Here’s the full, working version of your class:

using System.Configuration;
using System.Data.SqlClient;

class DBConnection
{
    private readonly string _connectionString;

    public DBConnection()
    {
        // Pull the connection string directly from App.config
        _connectionString = ConfigurationManager.ConnectionStrings["connectionstr"].ConnectionString;
    }

    // Helper method to get a ready-to-use connection
    public SqlConnection GetConnection()
    {
        return new SqlConnection(_connectionString);
    }
}

Key points here:

  • Add using System.Configuration; to access the ConfigurationManager tool
  • The name inside ["connectionstr"] must match exactly what you defined in your config file
  • Using readonly makes the connection string immutable, which is safer for your app

3. Ensure your App.config is properly formatted

Your provided config snippet was missing closing tags—fix that, and add the providerName attribute (it helps with database operation compatibility):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <connectionStrings>
        <add name="connectionstr" 
             connectionString="Data Source=DESKTOP-F8UCLUB;Initial Catalog=bug_tracker;Integrated Security=True"
             providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

4. Best practice for using the connection

When writing your CRUD logic, always wrap the connection in a using statement. This guarantees the connection gets closed and cleaned up properly, even if an error occurs:

// Example: A simple read operation
using (var conn = new DBConnection().GetConnection())
{
    conn.Open();
    string query = "SELECT * FROM your_table_name";
    using (var cmd = new SqlCommand(query, conn))
    {
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // Process your data here
            }
        }
    }
}

Double-check that the connection string name in your code matches what’s in App.config—even small typos can cause this error!

内容的提问来源于stack exchange,提问作者Chris Hadfield

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:28:39