我有一个名为cmbWeekDays的ComboBox,一个WeekDay
类:
public class WeekDay
{
public int Index;
public string DayName;
}
和这个FormLoad事件:
List<WeekDay> days = new List<WeekDay>();
days.Add(new WeekDay { DayName = "Sat", Index = 1 });
days.Add(new WeekDay { DayName = "Sun", Index = 2 });
days.Add(new WeekDay { DayName = "Mon", Index = 3 });
days.Add(new WeekDay { DayName = "Tue", Index = 4 });
days.Add(new WeekDay { DayName = "Wed", Index = 5 });
days.Add(new WeekDay { DayName = "Thu", Index = 6 });
days.Add(new WeekDay { DayName = "Fri", Index = 7 });
cmbxWeekDays.DataSource = days;
cmbxWeekDays.DisplayMember = "DayName";
cmbxWeekDays.ValueMember = "Index";
cmbxWeekDays.Refresh();
我不知道为什么会得到这个奇怪的结果:
任何人都能解释我发生了什么吗?以及如何克服这个问题?
答案 0 :(得分:2)
数据绑定仅适用于属性。因此,您必须在数据源类中声明属性而不是字段:
public class WeekDay
{
public int Index { get; set; }
public string DayName { get; set; }
}
答案 1 :(得分:0)
尝试以下方式可能对您有所帮助。我也面临同样的问题。但我写了cmbyear.Databind()最后它适合我。所以尝试一次。
DropDownList cmbYear = new DropDownList();
cmbYear.DataSource = days;
cmbYear.DataTextField = "Year";
cmbYear.DataValueField = "YearID";
cmbYear.DataBind();