目前此测试窗口表单应用程序存在问题。构造函数用于将数据添加到 datagridview。但是,当我单击该按钮时,它无法添加任何内容来运行 sql 命令,并出现错误 ExecuteNonQuery: Connection property has not been initialized。下面是我的代码。我发现了类似问题的问题,但他们没有通过在代码中的多个点调用数据库来解决这个问题。
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();
}
}
}