我正在尝试用此选定月份中的日期填充ComboBox
private void cboSelectMonth_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboSelectMonth.SelectedIndex >= 0)
{
int year = Convert.ToInt32(cboSelectYear.SelectedValue);
int month = Convert.ToInt32(cboSelectMonth.SelectedValue);
this.cboSelectDay.DisplayMember = "Text";
this.cboSelectDay.ValueMember = "Value";
int dayCount = DateTime.DaysInMonth(year, month);
var days = new[ dayCount+1 ] { };
for (int i = 1; i < dayCount +1; i++)
{
days[i] = new { Text = Convert.ToString(i), Value = i };
//cboSelectDay.Items.Add(i);
// days[] { new { Text = Convert.ToString(i), Value = i } };
}
this.cboSelectDay.DataSource = days;
DateTime now = DateTime.Now;
int dayValue = now.Day;
cboSelectDay.SelectedIndex = dayValue - 1;
}
}
因此,我试图以ComboBox结尾,该框列出了当月的所有日期.例如,选择9月将增加30天的组合框,选择10月将给您31等.我遇到两个错误.第一个是在var days = new [dayCount 1] {}上;行,表示保护了“]”.第二个错误是在天[i] = new {Text = Convert.ToString(i),Value = i};行上,提示无法将类型’AnonymousType#1’隐式转换为’int’
我正在尝试做一些与我在月中所做的事情类似的方法,该方法确实有效(下面的代码块).我究竟做错了什么?
private void FillMonthCombobox()
{
this.cboSelectMonth.DisplayMember = "Text";
this.cboSelectMonth.ValueMember = "Value";
var months = new[]
{
new { Text = "January", Value = 1 },
new { Text = "February", Value = 2 },
new { Text = "March", Value = 3 },
new { Text = "April", Value = 4 },
new { Text = "May", Value = 5 },
new { Text = "June", Value = 6 },
new { Text = "July", Value = 7 },
new { Text = "Aughust", Value = 8 },
new { Text = "September", Value = 9 },
new { Text = "October", Value = 10 },
new { Text = "November", Value = 11 },
new { Text = "December", Value = 12 }
};
this.cboSelectMonth.DataSource = months;
DateTime now = DateTime.Now;
int monthValue = now.Month;
cboSelectMonth.SelectedIndex = monthValue - 1;
}
编辑:我现在可以填充ComboBox,但是如何将Text = day和Value = day添加到循环中,以便以后可以引用Value?在此循环中,它们将是相同的,但在我正在处理的其他一些循环中,它们将是不同的.本质上,我想在第二个代码块中做同样的事情,但要有一个循环.
解决方法:
很简单,但是您也必须指定年份.注意二月和and年!
int year = 2015;
int month = 5;
int[] days = Enumerable.Range(1, DateTime.DaysInMonth(year, month)).ToArray();
之后可以将其指定为数据源:
cboSelectDay.DataSource = days;
cboSelectDay.DataBind();