如何从对象列表中获取字符串值并将它们添加到下拉列表中?
本文关键字:添加 下拉列表 对象 列表 字符串 获取 | 更新日期: 2023-09-27 18:15:23
我想要一个包含3个部分的员工列表,员工id,姓和名,并将它们添加到显示姓,名的下拉列表中。
到目前为止,我已经为员工创建了一个类:
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
并创建了一个列表来填充:
private List<Employee> employeeList = new List<Employee>();
此列表由SQL查询填充,然后按姓氏排序。
foreach (DataRow row in ds.Tables["EMPLOYEE_TABLE"].Rows)
{
employeeList.Add(new Employee(int.Parse(row["EMP_ID"].ToString()),
row["LAST_NAME"].ToString(), row["FIRST_NAME"].ToString()));
}
employeeList.Sort(delegate(Employee E1, Employee E2) { return E1.lastName.CompareTo(E2.lastName); });
和之前的一切都按照我想要的那样工作,但是我不知道如何用列表中包含的姓和名值填充下拉列表。
代码已编辑为可读性
见下面的代码:
DropDownList ddl = new DropDownList();
ddl.DataSource = employeeList;
ddl.DataTextField = "fullName";
ddl.DataValueField = "emp_Id";
我也会修改你的类,包括一个全名字段:
public class Employee
{
public int emp_Id { get; set; }
public string lastName { get; set; }
public string firstName { get; set; }
public string fullName
{
get
{
return String.Format("{0} {1}", this.firstName, this.LastName);
}
}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
你可以在你的类中添加一个额外的属性来保存这3个值,并在绑定下拉列表时使用它作为你的DataTextField:
类代码
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public string Text
{
get { return this.ToString(); }
}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
public override string ToString()
{
return lastName + " " + firstName + " " + emp_Id;
}
}
HTML:
List<Employee> employees = new List<Employee>();
ddl.DataSource = employees;
ddl.DataValueField = "emp_Id";
ddl.DataTextField = "Text";
ddl.DataBind();
祝你好运!
已有属性的例子:
<asp:DropDownList id="bla" runat="server" />
bla.DataSource = employeeList;
bla.DataTextField = "firstName";
bla.DataValueField = "emp_Id"
bla.DataBind();
我推荐这样做:
<asp:DropDownList id="bla" runat="server" />
bla.DataSource = employeeList;
bla.DataTextField = "fullName";
bla.DataValueField = "emp_Id"
bla.DataBind();
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public string fullName get{ return firstName + " " + lastName;}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
为什么不创建一个名为FullName的属性来获取"FirstName + ' ' + LastName"?这样就只需要处理一个字段,而不是两个。
如果您不想或不能修改Employee
,您也可以尝试以下内容:
var data = employee.Select (x =>
new KeyValuePair<int, string>(
x.emp_Id,
string.Format("{0}, {1}", x.lastName, x.firstName)
));
ddl.DataSource = data.ToList();
ddl.DataValueField = "Key";
ddl.DataTextField = "Value";
ddl.DataBind();
这也可能是有用的,如果你有不同的页面不同的下拉菜单的员工,有时姓氏在前面,有时名字在前面,可能有或没有冒号在中间…