1

I have 2 table like this,

tbl_motor

motor_id     motor_types
--------------------------
1            audi
2            Ferrari

tbl_employee

employee_id   employee_name   motor_id
--------------------------------------
1             jack            2
2             john            1

But I have problem. I used combo_box on my register.
My combo box query is select motor_types from tbl_motor.

How to insert new value to tbl_employee which is my combo box is string emmmm I mean parse that string to int.

Mr MD
  • 31
  • 5
  • 'emmmm I mean parse that string to int..' - ? – P.Salmon May 06 '19 at 05:39
  • 2
    That should be a question about the part in the program logic. Make sure your combobox uses the object with the ID and not just the texts. – juergen d May 06 '19 at 05:41
  • As @juergend says, populate the combobox with both the ids and text. For example: `` When submiting to the server, you'd have the id to reference when inserting to tbl_employee. – Ultimater May 06 '19 at 05:49
  • I just followed the steps from this tutorial https://www.youtube.com/watch?v=fqpp3hXBZVI , Im just can't implement it(object id) into mysql. – Mr MD May 06 '19 at 06:06
  • related: [Populating a ComboBox using C#](https://stackoverflow.com/q/2417960/9260725) and [How to bind a List to a ComboBox?](https://stackoverflow.com/q/600869/9260725) – xdtTransform May 06 '19 at 06:54

1 Answers1

1

A ComboBox can contain objects of any type. You should avoid setting adding texts as items. Add your motors instead.

You propably have a class like this:

class Motor
{
    public int MotorId { get; set; }
    public string MotorType { get; set; }

    public override string ToString() // Important to override. This will be used to show the text in the combobox
    {
        return this.MotorType;
    }
}

And this is how you add Motors and read the SelectedItem:

// This is your Array which you got from your DB
Motor[] motors = new Motor[]
{
    new Motor() { MotorId = 1, MotorType = "Audi" },
    new Motor() { MotorId = 2, MotorType = "Ferrari" },
};

// We clear old items and add the motors:
this.comboBox1.Items.Clear();
this.comboBox1.Items.AddRange(motors);

// Select something for demonstration
this.comboBox1.SelectedIndex = 1;

// Read the selected item out of the combobox
Motor selectedMotor = this.comboBox1.SelectedItem as Motor; 

// Let's have a look what we got
MessageBox.Show(selectedMotor.MotorId + ": " + selectedMotor.MotorType);
kara
  • 3,205
  • 4
  • 20
  • 34