用了selectedValue C#套装组合项目 [英] C# Set combo item with selectedValue
问题描述
我是动态创建一个像这样的组合框:
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;
}
现在的问题是,当执行 cmb.SelectedValue = givenAnswers [0] .AnswerId;
cmb.SelectedValue总是空。
The problem is,when executing cmb.SelectedValue = givenAnswers[0].AnswerId;
cmb.SelectedValue is always null.
在调试和我探讨答案
(数据源)我看到ID(ValueMember)是exactle一样AnswerId(if语句)。两者有相同的类型(长)和相同的价值,但停留的SelectedValue空。
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.
有什么事我不知道?
编辑:
它看起来像组合框保持为空。当我把 cmb.SelectedValue = givenAnswers [0] .AnswerId;
与 cmb.SelectedIndex = 0;
我得到一个ArgumentOutOfRangeException。而这个问题的答案集合数是2,所以数据源不为空...非常strenge呵呵
It looks like the combobox stays empty. When I replace cmb.SelectedValue = givenAnswers[0].AnswerId;
with cmb.SelectedIndex = 0;
I get an ArgumentOutOfRangeException. This while the answers collections count is 2. So the datasource isn't null... Very strenge huh?
解决方案:
的SelectedValue,SelectedIndex的,性能的SelectedItem不能设置直到控件添加到窗体。后该控件添加到窗体中,selectedValue,则 - 索引和-Item属性进行设置。
The SelectedValue, SelectedIndex, SelectedItem properties can't be set until the control is added to the form. After the control is added to the form, the selectedValue, -Index and -Item properties can be set.
推荐答案
解决方案:
的SelectedValue,SelectedIndex的,性能的SelectedItem不能设置直到控件添加到窗体。之后,控制被添加到形式中,selectedValue,则 - 索引和-Item属性可设置
The SelectedValue, SelectedIndex, SelectedItem properties can't be set until the control is added to the form. After the control is added to the form, the selectedValue, -Index and -Item properties can be set.
这篇关于用了selectedValue C#套装组合项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!