-2

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

stuartd
  • 70,509
  • 14
  • 132
  • 163
morgh
  • 59
  • 6
  • 2
    when you trace it - exactly which line is erroring, what is the value of all the items at that point? – BugFinder Mar 02 '17 at 11:36

1 Answers1

3

You must first call connectToDatabase():

private void InsertData(object sender, EventArgs e)
{
        connectToDatabase()
        car = new Car();
        car.newBrand = txtBrand.Text;
        car.newName = txtName.Text;
        car.newRegisteredYear = txtYear.Text;
        dataBaseConnection.Insert(car);
}
apomene
  • 14,282
  • 9
  • 46
  • 72