填充 ComboBox(3 层架构)

时间:2021-01-26 07:38:07

标签: c# 3-tier

我对 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。

1 个答案:

答案 0 :(得分: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";
}

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