Question

I am trying to add an item and value to an asp.net dropdownlist control.

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));
}  

I get two error messages :

'System.Web.UI.WebControls.ListItem.ListItem(string, string)' has some invalid arguments

and

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

Any ideas what the issue(s) would be ?

Was it helpful?

Solution

You're trying to add the arrays as a whole to the ListItem value. I suspect they're supposed to be linked:

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]));
}  

You may also want to consider checking that they're the same length:

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

EDIT: Could throw in some Linq if you want though not really necessary:

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));
}

OTHER TIPS

Assuming you're arrays are always equal length and match one to one (between a name and id):

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

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

You were sending the arrays in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top