Question

Currently having an issue with this test windows form application. The constructor works to add data to a datagridview. However, when I click the button, it fails to add anything to run the sql command with the error ExecuteNonQuery: Connection property has not been initialized. Below is my code. I have found questions with similar issues but they do not address this issue with calling the database at multiple points in the code.

namespace TestApplication
{
public partial class Form1 : Form
{
    public SqlDatabase db;
    string myConnectionString = ConfigurationManager.ConnectionStrings["DF06Data_Tools"].ToString();
    public Form1()
    {
        InitializeComponent();
        db = new SqlDatabase(myConnectionString);
        UpdateGrid();

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    public void UpdateGrid()
    {
        string sql = "SELECT *  FROM [Data_Tools].[dbo].[TestTable]";
        DbCommand cmd = db.GetSqlStringCommand(sql);
        DataSet TableDataSet = db.ExecuteDataSet(cmd);
        dataGridView1.DataSource = TableDataSet.Tables[0];
        cmd.Dispose();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string sql = "INSERT INTO [Data_Tools].[dbo].[TESTTABLE] (name, id) VALUES('bob', '8')";
        DbCommand cmd = db.GetSqlStringCommand(sql);
        cmd.ExecuteNonQuery();
        UpdateGrid();
    }
}
}
Was it helpful?

Solution

You need to open your connection before calling ExecuteNonQuery. The call in your constructor opens the connection, issues the command, and then closes the connection for you.

From MSDN:

The call to ExecuteDataSet opens a connection, populates a DataSet, and closes the connection before returning the result.

Also from MSDN:

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top