Search code examples
c#sqlcomboboxprimary-keyauto-increment

C# Auto Increment Primary Key with String?


I am newbie to C# and programming...

When form loading primary key has to load automatically to comboBox and it has to automatically generate +1 from last value.. for example if COUNT value is 0 then it has to add like this EMP01

Here's my code:

class PrimaryKeyIncrement
{
    public void empPrimary() {
        Dbconnection ObjDb = new Dbconnection();
        ObjDb.ConnectWithDB();

        string empPri = "SELECT COUNT(EmployeeID) AS PK FROM Employees";
        SqlCommand Pri = new SqlCommand(empPri, ObjDb.conct);
        SqlDataReader rd = Pri.ExecuteReader();

        if(rd.Read()){
            string pk = rd["PK"].ToString();

            int IC = Int32.Parse(pk);
            IC++;

            string empPK = ("EMP")+IC.ToString();

            EmployeesManager EM = new EmployeesManager();
            EM.cmbEmployeeID.Items.Add(empPK).ToString();

        }        
    }

and i called empPrimary() method in EmployeesManager Form load.. There is no errors but nothing loading in the comboBox

Out put results Nothing showing in comboBox

Please help me Primary key should increase by one with String EMP


Solution

  • The actual cause of the issue you are having is because you are adding to a new EmployeeManager's combobox. You need to pass a reference to your form into your EmpPrimary

    ... EmpPrimary(this); //in your forms form load
    
    public void empPrimary(EmployeeManager form){ //change the method parameters
    
    form.cmbEmployeeID.Items.Add(empPK); // Now use the form reference in method
    

    As plutonix has stated however, you should let the form handle the PK's itself