Data to string conversion

Asked

Viewed 76 times

4

I’m developing a project and I’m having a problem with a date-to-string conversion (I believe that’s it).

I am counting months between a date and another (algorithm obtained in this other question, if you want a little more context).

But what’s going wrong is that I want to display this month count in a Textbox.

static int ajustaMesAno(DateTime d)
    {
        return d.Year * 12 + d.Month;
    }

 DateTime inicio = dtpvigencia.Value;
 DateTime fim = DateTime.Now;
 int mesesDiff = ajustaMesAno(fim) - ajustaMesAno(inicio);
   if (inicio.Day > fim.Day)
      {
          mesesDiff--;
      }
 mesesDiff = int.Parse(txtcontador.Text);

This instruction block is running inside a btncadastrar, I mean, when I click on it I should fill the Textbox txtcontador, but it does not happen. After clicking on the button it displays the error:

Input string was not in a correct format.

  • 1

    If you want to fill the Textbox txtcontator sure wouldn’t you do txtcontator.Text = mesesDiff.ToString()? You’re doing it backwards...

  • yes exactly that, I do not know where I was thinking right now, such a simple business mds, thank you very much, if you want to comment as reply I put as best answer

  • Normal, we often get lost in a few simple things...

1 answer

2


If I don’t understand your doubt wrong, you seem to be doing it contrary to what you need, do it this way:

static int ajustaMesAno(DateTime d)
{
    return ((d.Year * 12) + d.Month);
}

DateTime inicio = dtpvigencia.Value;
DateTime fim    = DateTime.Now;
int mesesDiff   = (ajustaMesAno(fim) - ajustaMesAno(inicio));

if (inicio.Day > fim.Day)
{
  mesesDiff--;
}

txtcontador.Text = mesesDiff.ToString();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.