我想根据从组合框中选择的年份(年份是数字)和月份(是文本)来获取天数。
年份组合框名称:cmbYear Month组合框名称:cmbMonth
代码触发事件:
private void cmbMonth_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbYear.SelectedIndex > -1)
{
{
var a = cmbDay;
a.Enabled = true;
a.BackColor = Color.LightCoral;
}
cmbMonth.BackColor = Color.Empty;
MethodLibrary.Fill_cmbDay(cmbYear,cmbMonth, cmbDay);
方法:
static class MethodLibrary //Method does not return something
{
public static void Fill_cmbDay(ComboBox strYear, ComboBox strMonth, ComboBox cmbTarget) //Void used does not return something
{
//Find how many days month has based on selected year & month. Convert month name to month number.
int days = DateTime.DaysInMonth(Convert.ToInt32(strYear.SelectedItem), Convert.ToInt32(strMonth.SelectedItem));
//Clear Combo box
cmbTarget.Items.Clear();
//Loop from 1 to number of days & add items to combo box
for (int i = 1; i <= days; i++)
{
cmbTarget.Items.Add(i);
}
}
}
用户窗体:
在线错误:
int days = DateTime.DaysInMonth(Convert.ToInt32(strYear.SelectedItem), Convert.ToInt32(strMonth.SelectedItem));
我相信在strMonth.SelectedItem转换为int32期间会发生错误。
帮助将不胜感激。
异常的原因是您尝试将"January"
字符串转换为整数值。尝试
int days = DateTime.DaysInMonth(
Convert.ToInt32(strYear.SelectedItem), // "2019" can be converted into 2019
strMonth.SelectedIndex + 1); // "January" can't; let's take Index then
我管理的内容对我有用:
代码触发器:
private void cmbMonth_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbYear.SelectedIndex > -1)
{
{
var a = cmbDay;
a.Enabled = true;
a.BackColor = Color.LightCoral;
}
cmbMonth.BackColor = Color.Empty;
int monthInDigit = DateTime.ParseExact(cmbMonth.SelectedItem.ToString(), "MMMM", CultureInfo.InvariantCulture).Month;
MethodLibrary.Fill_cmbDay(cmbYear, monthInDigit, cmbDay);
}
}
方法:
static class MethodLibrary //Method does not return something
{
public static void Fill_cmbDay(ComboBox strYear, int Month, ComboBox cmbTarget) //Void used does not return something
{
//Find how many days month has based on selected year & month. Convert month name to month number.
int days = DateTime.DaysInMonth(Convert.ToInt32(strYear.SelectedItem),Month);
//Clear Combo box
cmbTarget.Items.Clear();
//Loop from 1 to number of days & add items to combo box
for (int i = 1; i <= days; i++)
{
cmbTarget.Items.Add(i);
}
}
}