Home > Software engineering >  Cannot insert value from combobox into database
Cannot insert value from combobox into database

Time:11-25

I have a class Vehicle with the next property and constructor:

public VoertuigType VoertuigType { get; private set; } 
   
public Voertuig(VehicleType vt)
    {
        
        SetVehicleType(vt);
        
    }

SetVehicleType:

public void ZetVoertuigType(VehicleType vt)
    {
        if (vt== null) { throw new Exception("Vehicle- can't be null"); }
        VehicleType = vt;
    }

But then in mij WPF I select the VehicleType from a combobox. But when I try to insert the vehicletype into my db, I get this error:

System.Exception: 'Failed to convert parameter value from a VoertuigType to a String.'

What I do in the WPF to insert is:

private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        VehicleType t = new VehicleType(cmbType.SelectedValue.ToString());
        Vehicle v = new Vehicle(t);
        try
        {
            _vehicleManagerManager.AddVehicle(v);
            MessageBox.Show("Vehicle is added!");
        }
        catch (Exception ex) { throw new Exception(ex.Message); }//MessageBox.Show(ex.Message); }

        new MainWindow().Show();
        Close();
    }

Can anyone help me how I can fix this problem?

CodePudding user response:

Just convert your ComboBoxItem to VehicleType

VehicleType t = (VehicleType)cmbType.SelectedItem;

P.S. You need ComboBoxItems to be VehicleType

CodePudding user response:

@Tam Bui

public VoertuigType VoertuigType is supposed to be VehicleType vehicleType. The constructor of VehicleType is:

public VehicleType(string type)
    {
        SetType(type);
    }

SetType method in class VehicleType:

public void SetType(string type)
    {
        if (string.IsNullOrWhiteSpace(type)) { throw new VehicleException("May not be empty!"); }
        Type = type;
    }

The xaml:

TextBlock Text="Type:" FontSize="16" VerticalAlignment="Center" Margin="10,0"/>

ComboBox Name="cmbType" Width="130"  Margin="10,5,10,5" FontSize="16" />

The code for add vehicle is:

public void AddVehicle(Vehicle)
    {            
        SqlConnection conn = new SqlConnection(_connString);
        string query = "USE [Project_Flapp_DB]; INSERT INTO [dbo].[Voertuig] ([type]) VALUES "  
            "(@type);";
        using (SqlCommand cmd = conn.CreateCommand())
        {
            conn.Open();
            try
            {                    
                cmd.Parameters.Add(new SqlParameter("@type", SqlDbType.NVarChar));                   
                
                cmd.CommandText = query;      

                cmd.Parameters["@type"].Value = v.vehicleType;                    
                cmd.ExecuteNonQuery();
                
            }
            catch (Exception ex) { throw new Exception(ex.Message); }
            finally { conn.Close(); }
        }
    }

The exception was thrown on the btnAdd event.

  • Related