Home > Software design >  Add combo box items from other class to main form in Visual Studio C# forms?
Add combo box items from other class to main form in Visual Studio C# forms?

Time:03-31

I have a class that runs SQL query and add items to combo box by calling my main form combo box. But after I run my program my combo box is not populated.

Here is my main form code.

private void frmMain_Load(object sender, EventArgs e)
{
    con.getPrinID();
}

Here is my C# class code

public void getPrinID()
{
    main = new frmMain();

    con.Open();

    sda = new SqlDataAdapter("SELECT RTRIM(LTRIM(ClassID)) AS ClassID FROM ProductClass", con);
    dt = new DataTable();
    sda.Fill(dt);

    foreach (DataRow row in dt.Rows)
    {
        main.cmbPrin.Items.Add(row["ClassID"].ToString());
    }

    con.Close();
}

CodePudding user response:

despite being a bad solution, to get this done you have to pass the form reference, not create a new one.

pass this as a parameter to the function getPrinID().

private void frmMain_Load(object sender, EventArgs e)
{
    con.getPrinID(this);
}

set frmMain as expected parameter to the function.

public void getPrinID(frmMain main)
{
    con.Open();

    sda = new SqlDataAdapter("SELECT RTRIM(LTRIM(ClassID)) AS ClassID FROM ProductClass", con);
    dt = new DataTable();
    sda.Fill(dt);

    foreach (DataRow row in dt.Rows)
    {
        main.cmbPrin.Items.Add(row["ClassID"].ToString());
    }

    con.Close();
}

remember that the combobox cmbPrin access level must be set to public.

  • Related