1

I have a combobox in form5 and the script is below.

string sql = "SELECT * FROM `stock` WHERE `status`='1' AND `jml_stock`>'0'";
string sql2 = "SELECT * FROM `pelanggan`";
        
MySqlConnection mcon = new MySqlConnection(con);
mcon.Open();

MySqlCommand comm = new MySqlCommand(sql, mcon);

MySqlDataReader dr = comm.ExecuteReader();

while (dr.Read())
{
    string id_stock = dr["id_stock"].ToString();
    string nama = dr["nama_produk"].ToString();
    barang.Items.Add(nama);
    barang.ValueMember = id_stock;
    barang.DisplayMember = nama;
}

mcon.Close();

I want to retrieve data from the combobox above using this script.

id_stock = barang.SelectedValue.ToString();

but I get an error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

What do you think did I do wrong?

Cid
  • 14,968
  • 4
  • 30
  • 45
Haryo
  • 23
  • 3
  • This is winforms or? You misunderstood the meaning of `ValueMember` and `DisplayMember`; these should be the names to two properties of the object you added to the Items collection. – Klaus Gütter Dec 28 '20 at 07:16
  • yeah this is winform. idk, i google and get like that. actually it works for last index in combobox, but i cant get value member of index 0. do you have any reference for problem like that ? – Haryo Dec 28 '20 at 07:35
  • https://stackoverflow.com/questions/14248303/c-sharp-how-to-show-name-and-insert-values-names-id-from-combobox-in-c-sharp – Klaus Gütter Dec 28 '20 at 07:37
  • thanks, Klaus, your reference is very useful. – Haryo Dec 28 '20 at 07:47

1 Answers1

0

You can try following code

  barang.ValueMember = "id_stock";
    barang.DisplayMember = "nama_produk";

Also you can see following article.

https://www.c-sharpcorner.com/UploadFile/mahesh/combobox-in-C-Sharp/

Tech-leo
  • 62
  • 5