ConnectionString 属性尚未初始化。刷新gridView时出现

Mah*_*oud 1 c# datagridview winforms

我正在尝试dataGridView使用数据库中的数据填充 a ,它必须在加载表单和refreshButton单击时获取数据。

这是代码:

public partial class PhoneBookMainWindow : Form
{
    static public string connString = "Server=(local); Database=PhoneBook; Trusted_Connection=TRUE";
    public SqlConnection connection = new SqlConnection(connString);
    private void btnRefreshPhoneBook_Click(object sender, EventArgs e)
    {
        SqlCommand command = new SqlCommand("SELECT ID, contactName, jobTitle, currentAddress, workAddress, workPhone, cellPhone FROM ContactsInformations", connection);
        try
        {
            SqlDataAdapter dataAdapter = new SqlDataAdapter();
            dataAdapter.SelectCommand = command;
            DataTable dataSet = new DataTable();
            dataAdapter.Fill(dataSet);
            BindingSource bindingSrc = new BindingSource();

            bindingSrc.DataSource = dataSet;
            dataGridView1.DataSource = bindingSrc;
            dataAdapter.Update(dataSet);
        }
        catch (Exception x)
        {
            MessageBox.Show(x.Message);
            throw;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

我在Form loading& 中使用相同的代码btn clicking并且它们在执行中正常工作,但是当我从数据库中删除一行时出现问题(使用单击 a 查询delete btn然后单击refresh btn展览来到我面前。

Dav*_*vid 5

您似乎面临的问题是您有多个代码块共享同一个SqlConnection对象。撇开潜在的竞争条件不谈,这意味着它们中的任何一个都可能会在另一个对象使用它之前尝试处理该对象。

处置后,该对象不再处于可以使用它的状态。特别是在这种情况下,它不再有.ConnectionString集合。

本质上,这正在发生:

  • A类初始化连接
  • 方法A1使用连接
  • 方法A1完成连接并处理
  • 方法 A2 尝试使用连接,但不能,因为它已被释放

创建SqlConnection对象并不是一个特别耗费资源的过程,因此最好将它的范围限定在将要使用它的代码的本地范围内。像这样的东西:

using (SqlConnection connection = new SqlConnection(connString))
{
    using (SqlCommand command = new SqlCommand("SELECT ID, contactName, jobTitle, currentAddress, workAddress, workPhone, cellPhone FROM ContactsInformations", connection))
    {
        try
        {
            SqlDataAdapter dataAdapter = new SqlDataAdapter();
            dataAdapter.SelectCommand = command;
            DataTable dataSet = new DataTable();
            dataAdapter.Fill(dataSet);
            BindingSource bindingSrc = new BindingSource();

            bindingSrc.DataSource = dataSet;
            dataGridView1.DataSource = bindingSrc;
            dataAdapter.Update(dataSet);
        }
        catch (Exception x)
        {
            MessageBox.Show(x.Message);
            throw;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里做了两件事:

  1. SqlConnection对象在方法的内部,而不是在类级创建。这意味着除了这个方法会使用它之外什么都没有。(所以除了这个方法没有什么可以打破它。)
  2. 我在using语句中包装了一些一次性对象,这是处理任何实现IDisposable.