2

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?

1 Answer 1

4

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
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Truthfully I wasn't aware of AddRange. I guess adding the items one at a time would have worked too and DataBind is the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.