Reputation: 363
Creating a Windows Forms Application in C#, I have a program that I am trying to insert a date into a text box (textBox3), and I can't get the date to show up. I created a button on the form that pops up, and the date shows up just fine. But, the text box never populates. Any suggestions? Here's the code:
private void textBox3_TextChanged(object sender, EventArgs e)
{
var today = DateTime.Today.ToString("dd/MM/yyyy");
textBox3.Text = today;
}
private void button1_Click(object sender, EventArgs e)
{
var today = DateTime.Today.ToString("MM/dd/yyyy");
MessageBox.Show("Today is " + today + ".");
}
Upvotes: 1
Views: 3500
Reputation: 363
First off, thanks to anyone that gave me a response without doing it in a question. I understand where the questions are directed, but they only confuse the already confused. I learn by doing things, so direct answers are GREATLY appreciated!
However, I got around the issue of needing to type in the field to have it populate the date, by pre-loading the text on load! So, Icarus you are correct. I wanted to assume the user might not type in the date box at all. (trying to make it failproof)
Thanks again, all! :-)
**private void Form1_Load(object sender, EventArgs e)**
{
try
{
{
textBox2.Text = "Date";
}
{
catch (System.Exception ex)
}
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
The rest was easy . . .
**private void textBox2_TextChanged(object sender, EventArgs e)**
{
var date = DateTime.Now.ToString("MM/dd/yyyy");
textBox2.Text = date;
}
Upvotes: 0
Reputation: 31887
The code you have will only work when you type something on it. The reason is that you are filling your Textbox.Text in the TextChanged event (when the user types something in the textbox).
What I guess you want to do is to assign the Text property after InitializeComponent in your form, or any other initialization stuff such as FormLoad:
public MyForm()
{
InitializeComponent();
InitializeDates();
}
public void InitializeDates()
{
var today = DateTime.Today.ToString("dd/MM/yyyy");
textBox3.Text = today;
}
Upvotes: 2
Reputation: 63962
Your text field will only update when you start typing anything on the textbox because, apparently, you are hooking up to the Text_Changed event.
Type something in textBox3
and you'll see that the text becomes whatever today
is holding.
Upvotes: 0