i have set combobox displaymember and valuemember.
now i want to store id in DB instead of fieldname , how?

Dani AI

Generated

As suggested, the right approach is to bind the ComboBox so the numeric key is the ValueMember and the visible text is the DisplayMember. 's DataRowView technique works, but the simpler, idiomatic pattern in WinForms is to read the bound value via SelectedValue, validate it, then send that integer to the database with a parameterized query.

Recommended steps:

  • Bind a DataTable or a list of objects that contains both the id and the display text. Ensure the ValueMember matches the id column/property and the DisplayMember matches the text column/property.
  • Read comboBox1.SelectedValue, check for null, and convert to an int safely.
  • Use a parameterized MySQL command to insert/update the integer foreign key (avoid string concatenation).
  • In the database use an INT column for the FK, index it and enforce referential integrity with an InnoDB foreign key if appropriate.

Example C# pattern (WinForms + MySql.Data):

object raw = comboBox1.SelectedValue;
int selectedId;
if (raw != null && int.TryParse(raw.ToString(), out selectedId))
{
    using (var conn = new MySqlConnection(connString))
    using (var cmd = new MySqlCommand(
        "INSERT INTO products (category_id, name) VALUES (@catId, @name)", conn))
    {
        cmd.Parameters.Add("@catId", MySqlDbType.Int32).Value = selectedId;
        cmd.Parameters.Add("@name", MySqlDbType.VarChar).Value = productName;
        conn.Open();
        cmd.ExecuteNonQuery();
    }
}

Database notes: store the FK as INT (use UNSIGNED if IDs are nonnegative), add an index, and use an InnoDB FOREIGN KEY to keep integrity. Parameterized commands prevent SQL injection and type errors.

Recommended Answers

All 2 Replies

Set the valuemember to the ID value.
Set the displaymember to the Name value.

Then use the valuemember instead of displaymember when writing the SQL to store it.

Retreive the id from the selected tiem, by using DataRowView class:

DataRowView view = comboBox1.SelectedItem as DataRowView;
int id = int.Parse(view["IdColumnName"].ToString());
//us id variable as a value to insert to db.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.