gpt4 book ai didi

c# - 尝试将项目和值添加到 asp.net 中的下拉列表时出错

转载 作者:太空宇宙 更新时间:2023-11-03 21:54:27 24 4
gpt4 key购买 nike

我正在尝试将项目和值添加到 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)' has some invalid arguments

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

知道问题是什么吗?

最佳答案

您正在尝试将数组作为一个整体添加到 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));
}

关于c# - 尝试将项目和值添加到 asp.net 中的下拉列表时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12904157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com