C# Set combo item with selectedValue

Posted by Martijn on Stack Overflow See other posts from Stack Overflow or by Martijn
Published on 2010-05-19T08:56:44Z Indexed on 2010/05/19 9:00 UTC
Read the original article Hit count: 184

Filed under:
|
|

I am dynamically creating a combobox like this:

public Control GenerateList(Question question)
{
    // Get a list with answer possibilities
    List<QuestionAnswer> answers = question.GetAnswers();

    // Get a collection of given answers
    Collection<QuestionnaireAnswer> givenAnswers = question.GetFilledAnswers();

    ComboBox cmb = new ComboBox();
    cmb.Name = "cmb";
    cmb.DataSource = answers;
    cmb.DisplayMember = "Answer";
    cmb.ValueMember = "Id";

    // Check an answer is given to the question
    if (givenAnswers != null && givenAnswers.Count > 0)
    {
        cmb.SelectedValue = givenAnswers[0].AnswerId;

    }

    cmb.DropDownStyle = ComboBoxStyle.DropDownList;
    cmb.SelectedIndexChanged += new EventHandler(cmb_SelectedIndexChanged);
    cmb.Leave += new EventHandler(cmb_Leave);

    return cmb;
}

The problem is,when executing cmb.SelectedValue = givenAnswers[0].AnswerId; cmb.SelectedValue is always null.

When debugging and I explore answers (the datasource) I see that Id (ValueMember) is exactle the same as AnswerId (in the if statement). Both have the same type (long) and the same value, but SelectedValue stays null.

Is there something I don't see?

© Stack Overflow or respective owner

Related posts about c#

Related posts about winforms