根据所选的年份和月份计算月份的天数

时间:2019-04-02 09:13:14

标签: c# combobox

我正在尝试根据从组合框中选择的年(年为数字)和月(为文本)获取天数。

年份组合框名称:cmb年份 月份组合框名称: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);
        }
    }
}

用户窗体:

enter image description here

在线错误:

int days = DateTime.DaysInMonth(Convert.ToInt32(strYear.SelectedItem), Convert.ToInt32(strMonth.SelectedItem));

我认为将strMonth.SelectedItem转换为int32时会发生错误。

会有所帮助。

enter image description here

2 个答案:

答案 0 :(得分:1)

该异常的根本原因是您尝试将"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  

答案 1 :(得分:0)

我所管理的东西对我有用:

代码触发器:

tableview.register(UITableViewCell.self, forCellReuseIdentifier: "groupCell")

方法:

    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);
        }
    }