Saima Maheen
Saima Maheen

Reputation: 132

How i Show DateTime in Label

I have a label, a textbox and a button on a form. I want to add days to the current date/time. The value of days is connected to the textbox and the datetime is shown on the label.

Double ce = Convert.ToDouble(textBox1.Text)
DateTime cs = DateTime.Now.AddDays(ce)

But it throws an error that the input is wrong.

Upvotes: 1

Views: 1048

Answers (2)

Random IT Guy
Random IT Guy

Reputation: 623

EDIT* Added Parse instead of Tryparse to show error instead of adding 0 days

        try
        {
            double days = double.Parse(textBox1.Text);
            label1.Text = DateTime.Now.AddDays(days).ToLongDateString();
        }
        catch (Exception ex) { MessageBox.Show(ex.Message, "error"); }

Upvotes: 1

rene
rene

Reputation: 42483

if you use TryParse you can check if the value in the string is ok to be converted. If it is not you can inform the user something went wrong.

Double days = 0;
DateTime cs= DateTime.Now;
bool daysOk = Double.TryParse(textbox1.Text, out days);
if (daysOk) 
{
   cs = cs.AddDays(days);
}
else
{
   textbox1.Text = "invalid days";
}

Upvotes: 2

Related Questions