我正在开发一个将数据插入和删除数据库的程序。数据库只有一张表,有四列(nombreEmpleados、apellidosEmpleados、departamento 和 carnet)。该程序有4个按钮,保存,删除,显示和关闭,问题是当我第一次单击显示或保存时,程序可以工作,但是当我再次执行此操作时出现此错误:连接字符串属性尚未初始化.
编辑 *这是从开始到保存按钮的代码:*
namespace sampleAdonetWinforms
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection("Data Source=MAINPC;Initial Catalog=Ambar;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
formBorrar ventanaBorrar = new formBorrar();
ventanaBorrar.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO empleados VALUES (@Nombre, @Apellidos, @Departamento, @Carnet)";
SqlCommand vCom = new SqlCommand(query, conn);
int carnetID = int.Parse(tbCarnet.Text);
try
{
vCom.Parameters.AddWithValue("@Nombre", tbNombre.Text);
vCom.Parameters.AddWithValue("@Apellidos", tbApellidos.Text);
vCom.Parameters.AddWithValue("@Departamento", tbDepartamento.Text);
vCom.Parameters.AddWithValue("@Carnet", carnetID);
tbNombre.Focus();
conn.Open();
vCom.ExecuteNonQuery();
vCom.Dispose();
MessageBox.Show("Data stored");
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex.Message);
}
}