简体   繁体   中英

How to display primary key in a combobox immediately after insert records to the database c#?

I'm developing a windows form application to insert datagridview values to sqldatabase.I would like to know how to display inserted value's primary key(GRN_No) in a combobox immediately after insert.I tried this for display GRN_No when I load form as well as after insert command.

void fillGRNcombo()
    {
        DynamicConnection con = new DynamicConnection();
        con.mysqlconnection();
        con.sqlquery("select GRN_No from TBL_GRN");
        con.dataread();
        while (con.datareader.Read())
        {
            cmbGRN.Items.Add((int)con.datareader["GRN_No"]);
        }
    }

But after insertation values duplicated in combobox like(1,2,1,2,3).How to solve this?

In your case your combo box persisting earlier data, that is the reason you can see repeated record in your combo box.

Instead of adding same data again and again, just clear combo box before adding new primary keys or new records to it.

  cmbGRN.Items.Clear();
  while (con.datareader.Read())
        {
            cmbGRN.Items.Add((int)con.datareader["GRN_No"]);
        }

Simply Clear ComboBox before Reading the DataReader

  cmbGRN.Items.Clear();    
  while (con.datareader.Read())
  {
       cmbGRN.Items.Add((int)con.datareader["GRN_No"]);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM