null reference error C#

Feb 28 2014 6:30 PM
I am having some nullreference error and i can't spot why, this is my entire function where im getting the error, the red highlight is where the error occurs

private void unidadesBtn_Click(object sender, EventArgs e)
        {
            var owner_response = proxy.GetOwners();

            if (owner_response != null)
            {
                DataTable vehicleData = new DataTable();
                foreach (var owner in owner_response.Owners)
                {
                    var vehicle_response = proxy.GetVehicles(owner.OwnerId);
                    if (vehicle_response != null)
                    {
                        vehicleData.Columns.Add("TypeDisplayName", typeof(SqlString));
                        vehicleData.Columns.Add("DefaultDriverId", typeof(Guid));
                        vehicleData.Columns.Add("VehicleId", typeof(Guid));
                        vehicleData.Columns.Add("OwnerId", typeof(Guid));
                        vehicleData.Columns.Add("DisplayName", typeof(SqlString));
                        vehicleData.Columns.Add("Description", typeof(SqlString));
                        vehicleData.Columns.Add("Registration", typeof(SqlString));
                        vehicleData.Columns.Add("Notes", typeof(SqlString));
                        vehicleData.Columns.Add("VehicleTypeId", typeof(Guid));
                        vehicleData.Columns.Add("VehicleProfileId", typeof(Guid));
                        vehicleData.Columns.Add("NotifyDriverOfGeofenceAlert", typeof(Boolean));
                        vehicleData.Columns.Add("IsProfile", typeof(Boolean));
                        vehicleData.Columns.Add("VehicleGroupId", typeof(Guid));
                        vehicleData.Columns.Add("CreatedDateTime", typeof(DateTime));
                        vehicleData.Columns.Add("ModifiedDateTime", typeof(DateTime));
                        vehicleData.Columns.Add("UserId", typeof(Guid));
                        vehicleData.Columns.Add("UniqueVehicleId", typeof(SqlString));
                        vehicleData.Columns.Add("DefaultVechileStateId", typeof(Boolean));
                        vehicleData.Columns.Add("GISCulture", typeof(SqlString));

                        foreach (var vehicle in vehicle_response.Vehicles)
                        {
                            vehicleData.Rows.Add(vehicle.TypeDisplayName.ToCharArray(), vehicle.DefaultDriverId, vehicle.VehicleId, vehicle.OwnerId,
                                vehicle.DisplayName.ToCharArray(), vehicle.Description.ToCharArray(), vehicle.Registration.ToCharArray(), vehicle.Notes.ToCharArray(),
                                vehicle.VehicleTypeId, vehicle.VehicleProfileId, vehicle.NotifyDriverOfGeofenceAlert, vehicle.IsProfile, vehicle.VehicleGroupId,
                                vehicle.CreatedDateTime, vehicle.ModifiedDateTime, vehicle.UserId, vehicle.UniqueVehicleID.ToCharArray(),
                                vehicle.DefaultVehicleStateID, vehicle.GISCulture.ToCharArray());
                        }
                        string nombre = owner.OwnerName;
                    }
                }
                if (vehicleData.Rows.Count > 0)
                {
                    SqlConnection con = new SqlConnection(@"Data Source=10.113.192.122\SQLEXPRESS;Initial Catalog=FOO;Persist Security Info=True;User ID=Navman;Password=Pato745477;Initial Catalog=Navman");
                    SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
                    bc.DestinationTableName = "Vehicles";
                    bc.BatchSize = vehicleData.Rows.Count;
                    con.Open();
                    SqlCommand cmd = new SqlCommand("DELETE FROM dbo.Vehicles");
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    cmd.ExecuteNonQuery();
                    bc.WriteToServer(vehicleData);
                    bc.Close();
                    con.Close();
                }
            }
        }


Answers (8)

1
Vulpes

Vulpes

  • 0
  • 96k
  • 2.5m
Feb 28 2014 7:46 PM
I think it must be the case that one (or more) of the strings to which you're applying the ToCharArray() method is null as all the other columns are simple values.

However, whilst I might be wrong, I don't think that you need to apply this method anyway to match the SqlString type as there are conversions defined between the .NET string type and the SqlString type. Null values though is another matter - see this MSDN link:

http://msdn.microsoft.com/en-us/library/ms172138(v=vs.110).aspx

Provided the columns concerned can tolerate null values within the database, what I'd suggest you do is to replace an expression such as this:

  vehicle.TypeDisplayName.ToCharArray()

with:

  (vehicle.TypeDisplayName != null) ? new SqlString(vehicle.TypeDisplayName) : SqlString.Null


Accepted Answer
0
Sanjay Dholakiya

Sanjay Dholakiya

  • 0
  • 84
  • 8.6k
Mar 2 2014 6:56 PM
Hi,

You have at lease one of following property with null value in it.

- TypeDisplayName

- DisplayName

- Description

- Registration

- Notes

- vehicle

- UniqueVehicleID

- GISCulture



- Sanjay 

0
Vulpes

Vulpes

  • 0
  • 96k
  • 2.5m
Mar 1 2014 12:56 PM
If it's nvarchar(50), then I'd try to set the MaxLength property again:

vehicleData.Columns.Add("TypeDisplayName", typeof(SqlString)).MaxLength = 50;

As it's no longer a fixed length column, you won't need to use PadRight and, as long as there's no chance of the TypeDisplayName property exceeding 50 characters, I'd expect the following to work now:

(vehicle.TypeDisplayName != null) ? new SqlString(vehicle.TypeDisplayName)) : SqlString.Null

If it could exceed 50 characters, then you'll need to use the Substring method to truncate it to the required size.

I'd only use a fixed length string type in the database if the values will always be exactly 'n' characters long. Otherwise I'd use varchar or nvarchar with 'n' set to the maximum conceivable length of the string, rounded up a bit to be on the safe side.





0
Patricio Llaguno

Patricio Llaguno

  • 0
  • 7
  • 2.1k
Mar 1 2014 11:36 AM
not nchar its nvarchar(50) it was nvarchar(10) before.. sorry, i wrote wrong, im really unsure what type of cariable i should be using in my database, what type should i use for 10 character strings? thx for your help, for real!
0
Vulpes

Vulpes

  • 0
  • 96k
  • 2.5m
Feb 28 2014 8:24 PM
Are you sure that particular column is an nchar(10) in the database?

If you are, then I'd forget about setting MaxLength and just go with PadRight.


0
Patricio Llaguno

Patricio Llaguno

  • 0
  • 7
  • 2.1k
Feb 28 2014 8:19 PM
i did that and i got this error now Cannot set column 'DisplayName'. The value violates the MaxLength limit of this column
0
Vulpes

Vulpes

  • 0
  • 96k
  • 2.5m
Feb 28 2014 8:07 PM
A good question :)

You could try something like this when adding your string columns:

vehicleData.Columns.Add("TypeDisplayName", typeof(SqlString)).MaxLength = 10;

This should work as the Add method returns a reference to the DataColumn added.

When adding the rows, you could then do:

(vehicle.TypeDisplayName != null) ? new SqlString(vehicle.TypeDisplayName.PadRight(10)) : SqlString.Null

which will pad out the string with spaces to an overall length of 10.


0
Patricio Llaguno

Patricio Llaguno

  • 0
  • 7
  • 2.1k
Feb 28 2014 7:49 PM
Very true indeed, this is the reason, i dont know how to convert into nchar(10) thats my sql target how can i do this?