winfrom动态生成的combox控件 绑定数据源之后 无法设置默认值问题
原代码:
List<student> ls = new List<student>();
student st = null;
for (int i = 0; i < 10; i++)
{
st = new student();
st.Id = i.ToString();
st.Name = "zj"+i;
ls.Add(st);
}
cl = new ComboBox();
((ComboBox)cl).DataSource = ls;
((ComboBox)cl).ValueMember = "id";
((ComboBox)cl).DisplayMember = "name";
(cl as ComboBox).SelectedIndex = 7;
this.Controls.Add(cl);
// 这样写之后 当程序运行到 (cl as ComboBox).SelectedIndex = 7;时报错。跟踪下cl为空。明明已经绑定了,怎么还是为空呢。
改进之后:
List<student> ls = new List<student>();
student st = null;
for (int i = 0; i < 10; i++)
{
st = new student();
st.Id = i.ToString();
st.Name = "zj"+i;
ls.Add(st);
}
cl = new ComboBox();
((ComboBox)cl).DataSource = ls;
((ComboBox)cl).ValueMember = "id";
((ComboBox)cl).DisplayMember = "name";
this.Controls.Add(cl);
(cl as ComboBox).SelectedIndex = 7;
//仔细观察,把 (cl as ComboBox).SelectedIndex = 7;放到 this.Controls.Add(cl);之后就可以了,结果运行正常。