I am getting an error that throws an exception called just like the title. Im not sure what is the problem
Connection:
public void connectToDatabase()
{
connStrBuilder = new SqlConnectionStringBuilder();
connStrBuilder.DataSource = @"DESK-KEGRC\SQLSERVER";
connStrBuilder.InitialCatalog = "RentalDatabase";
connStrBuilder.IntegratedSecurity = true;
connection = new SqlConnection(connStrBuilder.ToString());
}
public void Insert(Car car)
{
try
{
string commandText = "INSERT INTO dbo.Cars(Brand, Name, Year) VALUES (@Brand, @Name, @Year)";
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("@Brand", car.newBrand);
command.Parameters.AddWithValue("@Name", car.newName);
command.Parameters.AddWithValue("@Year", car.newRegisteredYear);
connection.Open();
command.ExecuteNonQuery();
}
catch
{
throw;
}
}
This is the event button to insert the data into the database
private void InsertData(object sender, EventArgs e)
{
car = new Car();
car.newBrand = txtBrand.Text;
car.newName = txtName.Text;
car.newRegisteredYear = txtYear.Text;
dataBaseConnection.Insert(car);
}
Error:
System.NullReferenceException: Object reference not set to an instance of an object. at ConnectToDatabase.DatabaseConnection.Insert(Car car) in C:\Users\Kopalnia\Desktop\C#\Program\VehicleRental\VehicleRental\Vehicle Rental\ConnectToDatabase\DatabaseConnection.cs:line 46 at Vehicl_Rental.AddACar.InsertData(Object sender, EventArgs e) in C:\Users\Kopalnia\Desktop\C#\Program\VehicleRental\VehicleRental\Vehicle Rental\Vehicl Rental\AddACar.cs:line 31