简体   繁体   English

C#asp.net从另一个列表创建字符串列表,该列表返回类对象的列表

[英]C# asp.net create string list from a another list which returns list of class objects

I have a list which returns class objects. 我有一个返回类对象的列表。 For dropdownlist data bind purpose I need to create string list from previous list. 出于下拉列表数据绑定的目的,我需要从上一个列表创建字符串列表。 My main requirement is I need to get two fields(datavalue,datatext) to the dropdownlist from database. 我的主要要求是我需要从数据库中获取两个字段(数据值,数据文本)到下拉列表。 Can someone help me to do this 有人可以帮我做这个吗

class RoleData
{
    public string id { get; set; }
    public string value { get; set; }
}

private List<RoleData> EmpRoleDataBind(){
        List<RoleData> RoleList = new List<RoleData>();
        if (conn.State.ToString() == "Closed")
        {
            conn.Open();
        }
        string query = "select emp_role_id,description from emp_role";
        MySqlCommand cmd = new MySqlCommand(query,conn);
        MySqlDataReader msdr = cmd.ExecuteReader();

        while (msdr.Read())
        {

            RoleList.Add(
                new RoleData()
                {
                    id = Convert.ToString(msdr["emp_role_id"]),
                    value = Convert.ToString(msdr["description"])
                }    
            );
        }
        msdr.Close();
        conn.Close();
        return RoleList;
    }

You can bind the DropDownList to your list and assign the class property names to DropDownList attributes DataValueField , and DataTextField 您可以将DropDownList绑定到列表,并将类属性名称分配给DropDownList属性DataValueFieldDataTextField

dropdownlist1.DataSource = EmpRoleDataBind();
dropdownlist1.DataValueField = "id";
dropdownlist1.DataTextField = "value";
dropdownlist1.DataBind();

As a additional Note 作为附加说明

  • You probably need to capitalize the first letter of Property, see MSDN article Property Naming Guidelines . 您可能需要大写Property的首字母,请参见MSDN文章Property Naming Guidelines
  • As the method EmpRoleDataBind returns list of Employee-Role records, I would name it GetEmpRoleData instead of EmpRoleDataBind as It does not bind the DropDownList . 由于方法EmpRoleDataBind返回Employee-Role记录的列表,因此我将其命名为GetEmpRoleData而不是EmpRoleDataBind因为它不绑定DropDownList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM