I'm trying to insert values in my database and whenever I try to add it, my program just crash, giving me an error that The ConnectionString property has not been initialized, but I properly initialise it. Here is my code:
private static string conStr = @"Data Source=(LocalDB)v11.0;AttachDbFilename=c:usersaldrindocumentsvisual studio 2013ProjectsMidtermAssignment_RamirezMidtermAssignment_RamirezMasterFile.mdf;Integrated Security=True";
SqlConnection myCon = new SqlConnection();
private int studId, year, units;
private string fName, lName, mName, course, payment;
public void insertRecord()
{
myCon.Open();
SqlCommand insertInfo = new SqlCommand("spInsertStudentInformation", myCon);
insertInfo.CommandType = CommandType.StoredProcedure;
insertInfo.Parameters.Add("@studId", SqlDbType.Int).Value = studId;
insertInfo.Parameters.Add("@fName", SqlDbType.VarChar).Value = fName;
insertInfo.Parameters.Add("@lName", SqlDbType.VarChar).Value = lName;
insertInfo.Parameters.Add("@mName", SqlDbType.VarChar).Value = mName;
insertInfo.ExecuteNonQuery();
myCon.Close();
myCon.Open();
SqlCommand insertData = new SqlCommand("spInsertStudentData", myCon);
insertData.CommandType = CommandType.StoredProcedure;
insertData.Parameters.Add("@studId", SqlDbType.Int).Value = studId;
insertData.Parameters.Add("@course", SqlDbType.VarChar).Value = course;
insertData.Parameters.Add("@year", SqlDbType.Int).Value = year;
insertData.Parameters.Add("@units", SqlDbType.Int).Value = units;
insertData.Parameters.Add("@payment", SqlDbType.VarChar).Value = payment;
insertData.ExecuteNonQuery();
myCon.Close();
}
Here is the code in my button:
myData.StudId = Convert.ToInt32(txtStudId.Text);
myData.FName = txtFName.Text;
myData.LName = txtLName.Text;
myData.MName = txtMName.Text;
myData.Course = cboCourse.SelectedItem.ToString();
myData.Year = Convert.ToInt32(cboYear.SelectedItem.ToString());
myData.Units = Convert.ToInt32(txtUnits.Text);
myData.Payment = cboPayment.SelectedItem.ToString();
myData.insertRecord();
and here is my stored procedures:
CREATE PROCEDURE [dbo].spInsertStudentData
@studId int,
@course varchar(50),
@year int,
@units int,
@payment varchar(50)
AS
INSERT INTO StudentData VALUES (@studId, @course, @year, @units, @payment)
RETURN 0
CREATE PROCEDURE [dbo].spInsertStudentInformation
@studId int,
@fName varchar(50),
@lName varchar(50),
@mName varchar(50)
AS
INSERT INTO StudentInformation VALUES (@studId, @fName, @lName, @mName)
RETURN 0
I'm studying databases recently in ASP.NET and this is what I'm doing, but I don't know why this is not running fine in C#.
See Question&Answers more detail:
os