tags:

views:

67

answers:

4

Suppose the current month is "Oct". I want that it will add one month in current month i.e it will show "Nov". For this my code is written below but it gives exception that Input string was not in a correct format.

So please correct the code?

if (Convert.ToInt32(ddlMonth.SelectedIndex ) <= Convert.ToInt32(DateTime.Now.AddMonths(1).ToString()))
            {
                TotalBalanceUptoSelectedPreviousMonth();
            }
+2  A: 

I'll go out on a limb and say that this is what you're looking for:

if(ddlMonth.SelectedIndex <= DateTime.Now.AddMonths(1).Month)
{
    TotalBalanceUptoSelectedPreviousMonth();
}

Instead of getting the date as a string and converting it, why not use the Month property of the DateTime struct (which is already an integer)?

(Oh...and SelectedIndex is already an integer as well, no need for the call to Convert)

Justin Niessner
+1  A: 

You need to use DateTime.Now.AddMonths(1).Month.
Also you do not need to use the ToString method wrapped in a Convert.ToInt32 method as this is already an integer.

Andy Rose
+2  A: 
Convert.ToInt32(DateTime.Now.AddMonths(1).ToString())

probably gives the exception since DateTime.Now.AddMonths(1).ToString() value is not castable to Int32.

Numenor
+4  A: 

This should probably work:

if (Convert.ToInt32(ddlMonth.SelectedIndex ) 
    <= Convert.ToInt32(DateTime.Now.AddMonths(1).ToString("M")))

    TotalBalanceUptoSelectedPreviousMonth();

However, it looks simpler like this:

if (Convert.ToInt32(ddlMonth.SelectedIndex) <= DateTime.Now.AddMonths(1).Month)
    Total...();
Ioannis Karadimas
@Ioannis - If it is December then DateTime.Now.AddMonths(1).Month returns 1 as the month has been changed to January whereas DateTime.Now.Month +1 returns 13.
Andy Rose
Thanks. I guess I didn't think about that. I'll edit accordingly.
Ioannis Karadimas
Good stuff, down vote rescinded.
Andy Rose