Populate ComboBox from Business class using C# in Windows Application

Last Reply 2 months ago By dharmendr

Posted 2 months ago

Hi sir,

How to access Combobox of another form in static class in c#

I added values from database to combo box in Vb.net like SelectStudent.ComboBox1.Items.Add(dr("AdmissionNo").ToString()).

have done through modules in vb.net

Imports MySql.Data.MySqlClient
Module retrieveModule
    Public Sub retrieveStudentsName()
        Try
            dbConnection()
            Sql = "SELECT * FROM tblstudents;"
            cmd = New MySqlCommand(Sql, conn)
            dr = cmd.ExecuteReader
            While dr.Read
                SelectStudent.ComboBox1.Items.Add(dr("AdmissionNo").ToString())
            End While
        Catch ex As MySqlException
            MsgBox(ex.Message)
        Finally
            dr.Close()
        End Try
    End Sub    
End Module

 

Posted 2 months ago Modified on 2 months ago

Hi PSowmiya,

Check this example. Now please take its reference and correct your code.

Database

I have made use of the following table Customers with the schema as follows.

I have already inserted few records in the table.

You can download the database table SQL by clicking the download link below.

Download SQL file

Code

Static Class to return items for populating ComboBox.

using System.Collections.Generic;
using System.Data.SqlClient;
public static class RetrieveModule
{
    public static List<string> retrieveCountries()
    {
        List<string> countries = new List<string>();
        SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=Test;Uid=sa;pwd=pass@123;");
        string Sql = "SELECT DISTINCT Country FROM Customers;";
        SqlCommand cmd = new SqlCommand(Sql, conn);
        conn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            countries.Add(dr["Country"].ToString());
        }
        conn.Close();

        return countries;
    }
}

Accessing the static class in form

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();           
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        List<string> countries = RetrieveModule.retrieveCountries();
        foreach (string country in countries)
        {
            cbCountries.Items.Add(country);
        }
    }

    private void Submit(object sender, EventArgs e)
    {
        string message = "Country: " + cbCountries.Text;
        MessageBox.Show(message);
    }
}

Screenshot