【问题标题】:C# - I try to connect my Database to DataGridView in form but there's an errorC# - 我尝试将我的数据库连接到表单中的 DataGridView 但出现错误
【发布时间】:2015-07-01 18:13:40
【问题描述】:

我是 C# 编程新手,一直在学习本教程:
https://www.youtube.com/watch?v=vQ2QjRr3toM

我正在使用 C# 和 SQL Server。
我正在尝试让我的 [User] 表显示在 datagridview 上。


表格代码:

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;

namespace Software
{
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SQLFunctions.Refresh(this.dataGridView1);
        }
    }
}

SQLFunction 类代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
using System.Windows.Forms;
using System.Configuration;

namespace Software
{
    static class SQLFunctions
    {
        static private SqlCeConnection connection = new SqlCeConnection("Software.Properties.Settings.DatabaseConnectionString");

        static public void Refresh(DataGridView _dataGridView)
        {
            try
            {
                connection.Open();
                SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter("SELECCT * FROM [User]", connection);
                DataTable dataTable = new DataTable();
                dataAdapter.Fill(dataTable);
                _dataGridView.DataSource = dataTable;
            }
            catch(SqlCeException exception)
            {
                MessageBox.Show(exception.ToString());
            }
            finally
            {
                connection.Close();
            }
        }
    }
}

App.config

<connectionStrings>
        <add name="Software.Properties.Settings.DatabaseConnectionString"
            connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True"
            providerName="System.Data.SqlClient" />
</connectionStrings>

我的问题是,当我尝试运行我的程序时,我收到一条错误消息,提示我的 SQLFunctions 类引发了异常。

System.TypeInitializationException was unhandled
    Message = "The type initializer for 'Software.SQLFunctions' threw an exception."
    Source = Software
    TypeName = Software.SQLFunctions
    StackTrace:
       at Software.SQLFunctions.Refresh(DataGridView _dataGridView)
       at Software.Form1.Form1_Load(Object sender, EventArgs e) in c:\Users\misaru02\Documents\Visual Studio 2012\Projects\Thesis\Software\frmUserMgmt.cs:line 22
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    InnerException:
       Message = "Format of the initialization string does not conform to specification starting at index 0."
       Source = System.Data
       StackTrace:
          at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
          at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)
          at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)
          at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
          at System.Data.SqlServerCe.SqlCeConnectionStringBuilder..ctor(String connectionString)
          at System.Data.SqlServerCe.SqlCeConnection.set_ConnectionString(String value)
          at System.Data.SqlServerCe.SqlCeConnection..ctor(String connectionString)
          at Software.SQLFunctions..cctor() in c:\Users\misaru02\Documents\Visual Studio 2012\Projects\Thesis\Software\SQLFunctions.cs:line 16

我该如何解决这个错误?我已按照教程中的步骤进行操作。 :(
请帮忙,因为这是我的论文,我只有有限的时间:'(

【问题讨论】:

  • 您使用的是 SQL Server 精简版吗?
  • 我不确定。我怎么知道?

标签: c# sql-server database datagridview


【解决方案1】:

仔细检查您的连接字符串。

您会在 InnerException 中注意到,有一条消息说明

初始化字符串的格式不符合规范 从索引 0 开始。

导致此异常的跟踪使我相信这里的连接字符串有问题。

可能有错字或报价问题。

【讨论】:

    【解决方案2】:

    那是因为你的构造函数的第一行有一个硬编码的字符串。您需要从配置文件中获取值,而不是传入配置条目的字符串值。

    static private SqlCeConnection connection = new SqlCeConnection(ConfigurationManager.ConnectionStrings["Software.Properties.Settings.DatabaseConnectionString"].ConnectionString);
    

    您可能还查看了您的 select 语句,关键字 select 拼写错误。

    【讨论】:

    • 谢谢!我已经尝试了您所说的并更正了我的 Select 语句,但我仍然收到 InnerException 消息错误,即“不支持关键字:'attachdbfilename'。”
    • 那是因为你的配置文件里还有乱码。
    【解决方案3】:

    从连接字符串看来,您没有使用 SQL Server CE。话虽如此,您应该使用 SqlConnection 而不是 SqlCeConnection

    static class SQLFunctions
    {
        static private SqlConnection connection = new SqlConnection("Software.Properties.Settings.DatabaseConnectionString");
    
        static public void Refresh(DataGridView _dataGridView)
        {
            try
            {
                connection.Open();
                SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM [User]", connection);
                DataTable dataTable = new DataTable();
                dataAdapter.Fill(dataTable);
                _dataGridView.DataSource = dataTable;
            }
            catch(SqlException exception)
            {
                MessageBox.Show(exception.ToString());
            }
            finally
            {
                connection.Close();
            }
        }
    }
    

    *您查询中的“SELECT”也拼写错误。

    编辑:

    不要对连接字符串进行硬编码。

    static private SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Software.Properties.Settings.DatabaseConnectionString"].ToString()););
    

    【讨论】:

    • 谢谢,我已经尝试过并更正了我的 Select 语句,但我仍然收到 InnerException 消息错误,因为“初始化字符串的格式不符合从索引 0 开始的规范。”跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2014-06-10
    • 2016-05-29
    • 1970-01-01
    相关资源
    最近更新 更多