我動態創建一個組合框是這樣的:C#套裝組合產品與了selectedValue
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總是空當。
當調試和我探索answers
(數據源)時,我發現Id(ValueMember)與AnswerId(在if語句中)完全相同。兩者具有相同的類型(長)和相同的值,但是SelectedValue保留爲空。
有什麼我看不到?
編輯:
它看起來像組合框保持爲空。當我將cmb.SelectedValue = givenAnswers[0].AnswerId;
替換爲cmb.SelectedIndex = 0;
時,我得到一個ArgumentOutOfRangeException。這個雖然答案集合計數是2.所以數據源不是空的......非常的強烈吧?
解決方案:
的的SelectedValue,SelectedIndex的,的SelectedItem屬性不能直到控制被添加到形式設置。將控件添加到窗體後,可以設置selectedValue,-Index和-Item屬性。
QuestionAnswer是一個子類。基類包含Id和Answer屬性,它們都是公共的getter和setter。 – Martijn 2010-05-19 09:09:10