如何将特定值从数据库加载到下拉列表?

时间:2017-01-06 04:18:39

标签: c# asp.net sql-server

我有一个返回数据的查询。实际上它必须只返回一行数据,但我必须从不同的表中获取几个记录,它们包含一个主要属性的多个值。根据查询,我得到几行。现在我想将其中一条记录(列的一个单元格)加载到下拉列表中。我该怎么办?
这是我的查询

select emp.[App_no] 
    ,emp.[EMP_CALLING_NAME]
    ,emp.[EMP_INI]
    ,emp.[EMP_SURNAME]
    ,emp.[EMP_TITLE]
    ,emp.[EMP_NAMES_INI]
    ,emp.[EMP_FULLNAME]
    ,emp.[EMP_NIC]
    ,emp.[EMP_dob]
    ,emp.[EMP_GENDER]
    ,emp.[NAT_CODE]
    ,emp.[EMP_MARITAL_STATUS] 
    ,emp.[EMP_DATE_JOINED]
    ,emp.[EMP_CONFIRM]
    ,emp.[CX_CODE]
    ,emp.[DSMG_CODE]
    ,emp.[CAQT_CODE]
    ,emp.[EMP_PER_ADDRESS1]
    ,emp.[EMP_PER_ADDRESS2]
    ,emp.[EMP_PER_ADDRESS3]
    ,emp.[EMP_PER_CITY]
    ,emp.[EMP_PER_TELEPHONE]
    ,emp.[EMP_PER_MOBILE]
    ,emp.[EMP_PER_PROVINCE]
    ,emp.[EMP_PER_DISTRICT]
    ,emp.[EMP_TEM_ADDRESS1]
    ,emp.[EMP_TEM_ADDRESS2]
    ,emp.[EMP_PER_ELECTORATE]
    ,emp.[EMP_TEM_ADDRESS3]
    ,emp.[EMP_TEM_CITY]
    ,emp.[EMP_PER_GD]
    ,bank.[BBRANCH_CODE]
    ,bank.[EBANK_ACC_NO]
    ,bank.[EBANK_ACC_TYPE_FLG]
    ,bank.[EBANK_ACTIVE_FLAG]
    ,bank.[LAST_MODIFIED_DATE]
    ,qual.[Qulif_code]
    ,lang.[lang_code]
    ,lang.[ability_type]
    ,ex.[From_date]
    ,ex.[To_date]
    ,ex.[Organization]
    ,ex.[designation]
    ,ex.[Cobtact_No]
    ,nation.[NAT_NAME]
    from [EMPLOYEE] emp, [EMP_BANK] bank,
    [QUALIF] qual, [LANG] lang,
    [Experience] ex, [NATIONALITY] nation
    where emp.App_no = bank.App_no and emp.App_no = qual.App_No 
    and emp.App_no = lang.App_no and nation.NAT_CODE = emp.[NAT_CODE]
    and emp.App_no = ex.App_no and emp.App_no=@num           

这是我绑定数据的方式

ddlDesignations.DataSource = ds.Tables[0];
ddlDesignations.DataTextField = "designation";
ddlDesignations.DataValueField = "designation";
ddlDesignations.DataBind();              

这是下拉列表的显示方式 image of the dropdownlist

2 个答案:

答案 0 :(得分:1)

这可能会成功

DataView view = new DataView(ds.Tables[0]);
DataTable distinctValues = view.ToTable(true, "designation");
ddlDesignations.DataSource = distinctValues;
ddlDesignations.DataTextField = "designation";
ddlDesignations.DataValueField = "designation";
ddlDesignations.DataBind();

这里,ToTable()中的第一个参数是一个布尔值,表示你是否想要不同的行。 ToTable()中的第二个参数是列名,我们必须根据这些列选择不同的行。只有这些列将在返回的数据表中。

答案 1 :(得分:0)

您可以将LINQ用于此

var distinctdesignations = ds.Tables[0].AsEnumerable()
                           .Select(row => new {
                             designation = row.Field<string>("designation")
                           })
                           .Distinct();


ddlFamilyMembers.DataTextField = "designation"; 
ddlFamilyMembers.DataValueField = "designation;  
ddlFamilyMembers.DataSource = distinctdesignations;
ddlFamilyMembers.DataBind();