如何从另一个班级

时间:2015-10-26 20:39:40

标签: c# winforms

如何将项目添加到Form1中的comboBox,但是将项目添加到该组合框的功能是在另一个类中?

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();
}

2 个答案:

答案 0 :(得分:1)

Form:

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;
        }
    }

Business Class:

class BusinessLayer
{
    private DataLayer _dataLayer;

    public BusinessLayer()
    {
        _dataLayer = new DataLayer();
    }

    internal List<string> GetCategories()
    {
        return _dataLayer.RetrieveCatagories();
    }
}

Data Layer (you can refactor and extract the connection to another method):

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;
    }


}

答案 1 :(得分:0)

你可以这样:

{% if xxx == "home_en" or xxx == "page_en" %}

//然后是表单

的类
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();
    }
}