0

I have a system which uses SQL server management with Visual Studio. The combo box shows the users name in the drop down and when you select the name the ID associated with the record should be populated into the combo box. When I then press save to run an update in the SQL, the system tries to save the name as the ID. Which does not work as it is not an integer.

On load of the form this code runs to show the name. On the button how do I convert back to the ID

try {
    var dcnn = new SqlConnection(dbconnection.DatabaseString);
    dcnn.Open();
    var command =
        new SqlCommand("select StudentID, Firstname, Surname from student;", dcnn);
    using (SqlDataReader reader = command.ExecuteReader()) {
        cbxstudent.DisplayMember = "Text";
        cbxstudent.ValueMember = "Value";
        var items = new List<Object>();

        while (reader.Read()) {
            items.Add(new { Text = reader[1].ToString() + " " + reader[2].ToString(),
                Value = reader[0].ToString() });
        }
        cbxstudent.DataSource = items;
    }
    dcnn.Close();
}
catch (Exception ex) {
    MessageBox.Show("" + ex);     
}
Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34
  • 1
    why would you want to have "name" as id?. many people can have the same name......, you might as well use the id to represent different individuals. – Ousmane D. Mar 06 '17 at 21:24
  • Reference [this SO answer](http://stackoverflow.com/questions/3762981/hidden-id-with-combobox-items). You want to create an object and store it within the ComboBox as a ComboBoxItem. The ID will be hidden, while the name is shown. Then, when you are updating the SQL, only use the Student ID for the update, not the name. – Ethilium Mar 06 '17 at 21:34
  • Can you share the code of savebutton Click where you are updating the record? – Chetan Mar 06 '17 at 21:55

0 Answers0