【问题标题】:Populate ComboBox (3 Tier Architecture)填充 ComboBox(3 层架构)
【发布时间】:2026-01-01 11:55:01
【问题描述】:

我对 3 层架构很陌生。 我正在练习使用 3 层架构创建一个 WinForms 应用程序。

我有一个旧项目需要将其转换为 3 层架构。 注册、登录、填充Datagridview、选择数据我都没有问题。

我的问题是如何填充我的 ComboBox。

void FrmLoginLoad(object sender, EventArgs e)
{
    Dropdowns.getRole(cmbUserRole);
}

下拉类

public static void getRole (ComboBox dd)
{
    SQLHelper sqlConnect = new SQLHelper();
    sqlConnect.DBConnection();
    try
    {
        if (sqlConnect.con.State == ConnectionState.Closed) {
            sqlConnect.con.Open();
        }
            
        SqlCommand cmd = new SqlCommand("SELECT Role FROM tbl_IT_RoleDescription",sqlConnect.con);
            
        using (SqlDataReader dr = cmd.ExecuteReader()){
            if (dr.HasRows) {
                while (dr.Read()) {
                    dd.Items.Add(dr["Role"].ToString());
                }
            } 
            dr.Close();
        }
        sqlConnect.con.Close();
        dd.SelectedIndex = 0;
    }
    catch(Exception ex)
    {
        MessageBox.Show("Error : " + ex.Message + "\n\nSend this issue to EUC Dev Team?", "Intake Tool", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
            sqlConnect.con.Close();
    }   
}

我尝试转换为 3 层架构, PL

private void frmLogin_Load(object sender, EventArgs e)
{
    BLL_UserRole.getRole(cmbUserRole);
}

BLL

public void getRole(ComboBox cmbUserRole)
{
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT Role FROM tbl_IT_RoleDescription";
    db.exeReader(cmd);
}

DAL

public DataTable exeReader(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    try
    {
        cmd.Connection = getCon();
        SqlDataReader dr;

        dr = cmd.ExecuteReader();
        dt.Load(dr);
        con.Close();

    }
    catch (Exception ex)
    {
        MessageBox.Show("Error : " + ex.Message + "\n\nSend this issue to EUC Dev Team?", "Intake Tool", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
            con.Close();
    }
    return dt;
}

我试图研究这个,所有的结果都是硬编码的,或者他们只是在 ComboBox 的集合属性中插入数据。但我想要的是 ComboBox 的数据来自 DB。

【问题讨论】:

    标签: c# 3-tier


    【解决方案1】:

    我想我有一个适合你的解决方案。将 DataTable 对象返回到 PL 层会很棒。但是,如果您不想这样做,那么您可以检查我的虚拟代码并尝试一下。也可以查看类似问题链接LINK

    public void getRole(ComboBox cmbUserRole)
    {
                DataSet myDataSet = new DataSet();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT Role FROM tbl_IT_RoleDescription";
                var temp=db.exeReader(cmd);
                myDataSet.Tables.Add(temp);
                cmbUserRole.DataSource = myDataSet.Tables["tbl_IT_RoleDescription"].DefaultView;
                cmbUserRole.DisplayMember = "Role";
    }
    

    注意:请检查链接,让我知道它是否有效。

    【讨论】:

    • 我刚刚将这一行 cmbUserRole.DataSource = myDataSet.Tables["tbl_IT_RoleDescription"].DefaultView; 更改为 cmbUserRole.DataSource = myDataSet.Tables[0];,因为我遇到了实例错误。谢谢!