c#数据源不能为空

c# Data source can not be empty

我使用以下代码在单击按钮时将 sqlite 数据库中的一组项目加载到数据网格视图中!当数据库的路径在代码中给出时,数据库已成功连接并加载数据。

 public Form1()
        {
            InitializeComponent();
            dbconnection = @" Data Source = D:\SQLite\SQLiteStudio\DB1.db ; version=3 ";
        }

但是当我通过获取路径作为文本框输入更改代码如下时,发生错误 "Data source can not be empty"。使用的文本框名称为dbtext,将上面代码中的相同路径复制粘贴到文本框!

public Form1()
        {
            InitializeComponent();
            dbconnection = @"Data Source="+dbtext.Text+";version=3";
        }

我该如何解决这个问题?

问题是您在表单初始化时设置它,其中文本框仍然是空的并且您设置了它的值。

设置 dbconnection = @"Data Source="+dbtext.Text+";version=3"; 加载数据的同一按钮的 Click 事件或文本框的 textchanged 事件。

您正在程序的构造函数中设置连接字符串:

public Form1()
{
    InitializeComponent();
    dbconnection = @"Data Source="+dbtext.Text+";version=3";
}

此时 TextBox 仍然是空的,变量 dbconnection 将如下所示:

dbconnection = "DataSource=;version=3";

(在调试器中检查)。

现在您正尝试在按钮单击事件上建立连接,但是到哪里呢?相反,您的代码应如下所示:

priavte void Button1_Click(object sender, EventArgs e)
{
    dbconnection = "Data Source="+dbtext.Text+";version=3";
    //Do stuff with the connection
}