3

我有一个名为 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();

我不知道为什么会得到这个奇怪的结果:

输出图像

谁能解释我发生了什么?以及如何克服这个问题?

4

2 回答 2

2

数据绑定仅适用于属性。因此,您必须在数据源类而不是字段中声明属性:

public class WeekDay
{
    public int Index { get; set; }
    public string DayName { get; set; }
}
于 2012-12-19T05:54:26.353 回答
0

尝试以下方法可能对您有所帮助。我也面临同样的问题。但我最后写了 cmbyear.Databind() 它对我有用。所以尝试一次。

 DropDownList cmbYear = new DropDownList();
        cmbYear.DataSource = days;  
        cmbYear.DataTextField = "Year";
        cmbYear.DataValueField = "YearID";
        cmbYear.DataBind();
于 2012-12-19T06:16:37.927 回答