I hope you forgive my beginner's head. I am having some problems with a code designed to open a connect to a SQL Server database.
As you can see frmManageAppointment
form is loaded from a different Winform. So far so good. Upon loading, the Connect()
part of the code kicks in and connects to my SQL Server database. So far so good.
I have a second script that load upon pressing the Save button on the form (basically saving a variety of textboxes and such). My guess is that the second instance of conn in the MakeAppointment
code somehow closed the connection, based on the error I am getting.
I know I am not handling the script correctly so I would appreciate some help.
namespace Scheduler1
{
public partial class frmManageAppointment : Form
{
public frmManageAppointment()
{
InitializeComponent();
}
private void frmManageAppointment_Load(object sender, EventArgs e)
{
Connect();
txtDBConnection.Text = "Connected";
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtSurname.Text))
{
MessageBox.Show("Απαιτείται το Επίθετο του Εξεταζόμενου!");
return;
}
if (MakeAppointment())
{
MessageBox.Show("Επιτυχής Προσθήκη!");
}
else
{
MessageBox.Show("Ανεπιτυχής Προσθήκη");
}
}
public void Connect()
{
string conString = "Data Source=DIMITRIS-PC\\DIMITRISSQL;Initial Catalog=AppointmentDB;Integrated Security=True";
SqlConnection conn = new SqlConnection(conString);
conn.Open();
if (conn.State == System.Data.ConnectionState.Closed)
{
MessageBox.Show("Closed");
}
else if (conn.State == System.Data.ConnectionState.Open)
{
MessageBox.Show("Open");
}
}
public Boolean MakeAppointment()
{
string conString = "Data Source=DIMITRIS-PC\\DIMITRISSQL;Initial Catalog=AppointmentDB;Integrated Security=True";
SqlConnection conn = new SqlConnection(conString);
string sql = "INSERT INTO Appointmentdbo(Date, Time, Name, Surname, DOB, PatientID, Comments) VALUES ('" + dtpDate.Value.Date.ToString("MM/dd/yyyy") + "','" + comboTime.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + dtpDOB.Value.Date.ToString("MM/dd/yyyy") + "','" + txtID.Text + "','" + txtComments.Text + "')";
SqlCommand cmd = new SqlCommand(sql, conn);
return cmd.ExecuteNonQuery() > 0;
}
}
}