ikask ikask - 1 year ago 103
ASP.NET (C#) Question

asp.net assign value to variable when text control value is changed

I have this code in the asp.net page that works assigning the value to dtStart, but how do I update the variable dtStart to what the user manually enters or modifies the datetime value in the txtStart control box? thanks.

protected void btnStart_Click(object sender, EventArgs e)
txtStart.Text = DateTime.Now.ToString();
dtStart = DateTime.Now;

Answer Source

If txtStart.Text contains text which should represent a DateTime then you can try to convert it to exactly that:

DateTime dt;
if (DateTime.TryParse(txtStart.Text, out dt))
    dtStart = dt;

If the value could be parsed to a DateTime, it will be set in the dtStart variable. If not, it won't be. (You can add an else clause, or invert the conditional entirely, to handle the condition where the string value couldn't be parsed to a DateTime.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download