1

我正在尝试将项目和值添加到 asp.net 下拉列表控件。

arrEmpName = HttpContext.Current.Session["EmployeeName"].ToString();
arrEmpID = HttpContext.Current.Session["EmpID"].ToString();
char[] separator = new char[] { ',' };

string[] sEmployeeName = arrEmployeeName.Split(separator);
string[] sEmpID = arrEmpID.Split(separator);

foreach (string s in sEmployeeName)
{
    ddlEmp.Items.Add(new ListItem(sEmployeeName, sEmpID));
}  

我收到两条错误消息:

'System.Web.UI.WebControls.ListItem.ListItem(string, string)' 有一些无效参数

Argument 1: cannot convert from 'string[]' to 'string'  

有什么想法会是什么问题?

4

2 回答 2

4

您正在尝试将数组作为一个整体添加到 ListItem 值中。我怀疑他们应该被联系起来:

string[] sEmployeeName = arrEmployeeName.Split(separator);
string[] sEmpID = arrEmpID.Split(separator);

for (int i = 0; i < sEmployeeName.Length; i++)
{
    ddlEmp.Items.Add(new ListItem(sEmployeeName[i], sEmpID[i]));
}  

您可能还需要考虑检查它们的长度是否相同:

if (sEmployeeName.Length != sEmpID.Length)
    throw new Exception("Number of employee names does not match the number of IDs!");

编辑:如果你愿意,可以加入一些 Linq,但不是真的必要:

var employees = Enumerable.Zip(arrEmployeeName.Split(separator), arrEmpID.Split(separator), (name, id) => new { Name = name, ID = id } );
foreach(var employee in employees)
{
    ddlEmp.Items.Add(new ListItem(employee.Name, employee.ID));
}
于 2012-10-15T21:19:16.860 回答
0

假设您的数组总是等长并且一对一匹配(在名称和 id 之间):

for (int i = 0; i < sEmployeeName.Length; ++i)
{
    var employeeName = sEmployeeName[i];
    var employeeId = sEmpID[i];

    ddlEmp.Items.Add(new ListItem(employeeName, employeeId));
}

你正在发送arrays

于 2012-10-15T21:22:36.250 回答