C# 使用 selectedValue 设置组合项 [英] 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.
在调试和探索 answers
(数据源)时,我看到 Id(ValueMember)与 AnswerId(在 if 语句中)完全相同.两者具有相同的类型(long)和相同的值,但 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.SelectedIndex = 0;
替换 cmb.SelectedValue = givenAnswers[0].AnswerId;
时,我得到一个 ArgumentOutOfRangeException.这虽然答案集合计数是 2.所以数据源不为空...非常强吧?
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、-Index 和 -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、-Index 和 -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.
这篇关于C# 使用 selectedValue 设置组合项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!