如何从另一个类向组合框添加项

本文关键字:组合 添加 另一个 | 更新日期: 2023-09-27 18:19:16

如何将项目添加到Form1中的组合框中,但将项目添加到该组合框的函数在另一个类中?

public void comboBox1_Categories_Load()
{
    SqlConnection con = new SqlConnection(connection_string);
    string select_string = "SELECT * FROM dbo.Categories";
    SqlCommand cmd = new SqlCommand(select_string, con);
    SqlDataReader myReader;
    con.Open();
    myReader = cmd.ExecuteReader();
    while (myReader.Read())
    {
        comboBox1.Items.Add(myReader[1]); 
    }
    myReader.Close();
    con.Close();
}

如何从另一个类向组合框添加项

格式:

public partial class Form1 : Form
    {
        private BusinessLayer _businessLayer ;
        public Form1()
        {
            InitializeComponent();
            _businessLayer = new BusinessLayer();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            var categories = _businessLayer.GetCategories();
            comboBox1.DataSource = categories;
        }
    }

业务类:

class BusinessLayer
{
    private DataLayer _dataLayer;
    public BusinessLayer()
    {
        _dataLayer = new DataLayer();
    }
    internal List<string> GetCategories()
    {
        return _dataLayer.RetrieveCatagories();
    }
}

数据层(您可以重构并提取到另一个方法的连接):

class DataLayer
{
    public const string ConnectionString = "my connection string";
    internal List<string> RetrieveCatagories()
    {
        List<string> items = new List<string>();
        using (SqlConnection con = new SqlConnection(ConnectionString))
        {
            string select_string = "SELECT * FROM dbo.Categories";
            SqlCommand cmd = new SqlCommand(select_string, con);
            con.Open();
            SqlDataReader myReader = cmd.ExecuteReader();
            while (myReader.Read())
            {
                items.Add(myReader[1].ToString());
            }
            myReader.Close();
        }
        return items;
    }

}

你可以这样写:

public static OtherClass()
{
    public void RetrieveData(ComboBox comboBox)
    {
        SqlConnection con = new SqlConnection(connection_string);
        string select_string = "SELECT * FROM dbo.Categories";
        SqlCommand cmd = new SqlCommand(select_string, con);
        SqlDataReader myReader;
        con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
    comboBox.Items.Add(myReader[1]); 
}
myReader.Close();
con.Close();
    }
}

//然后你的表单所在的类

public void comboBox1_Categories_Load()
{
    OtherClass.RetrieveData(comboBox1);
}