Question

I am setting an Asp.Net CheckBoxList like so:

        var objs = db.CoreObjectives.AsNoTracking().Where(n => n.Core_Target_ID == id && n.Current_Record == true);
        foreach (var o in objs)
        {
            ListItem item = new ListItem();
            item.Value = o.Core_Objectives_ID.ToString();
            item.Text = o.Objective;
            item.Selected = false;
            results.Add(item);
        }
        lstObjectivesCore.DataSource = results;
        lstObjectivesCore.DataBind();

I have debugged on the item.Value line and the o.Core_Objectives_ID is definitely an integer. But when I do this later on:

        foreach (ListItem item in lstObjectivesCore.Items)
        {
            if (item.Selected)
            {
                int id = Convert.ToInt32(item.Value);
                // Other code omitted
            }
        }

The item.Value is the same as the item.Text, a string value i.e. "This is an Objective"? Am I doing something wrong?

Was it helpful?

Solution

Why do you use DataBind? I would use the Items.AddRange

This worked for me (with extra testcode)

    List<ListItem> result = new List<ListItem>();
    for (int i = 0; i < 10; i++)
    {
        result.Add(new ListItem("t" + i.ToString(), i.ToString()));
    }

    CheckBoxList1.Items.AddRange(result.ToArray());

    foreach (ListItem item in CheckBoxList1.Items)
    {
        if (item.Selected)
        {
            int id = Convert.ToInt32(item.Value);
            // Other code omitted
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top