I have a TextBox
and a DateTimePicker
and I want the selected date in the DateTimePicker to be written in the TextBox
.
In short what do I need to write inside here?
private: System::Void Date_Text_TextChanged(System::Object^ sender, System::EventArgs^ e) {
}
The above code is for the TextBox
that I want to inherit the string from the DateTimePicker
. And the one below is for the DateTimePicker
itself.
private: System::Void dateTimePicker1_ValueChanged(System::Object^ sender, System::EventArgs^ e) {
}
I tried so many things but no matter what I did I could not make Text->
which is the command to place text in the TextBox
accept anything related to the DateTimePicker
.
I have a TextBox
and a DateTimePicker
and I want the selected date in the DateTimePicker to be written in the TextBox
.
In short what do I need to write inside here?
private: System::Void Date_Text_TextChanged(System::Object^ sender, System::EventArgs^ e) {
}
The above code is for the TextBox
that I want to inherit the string from the DateTimePicker
. And the one below is for the DateTimePicker
itself.
private: System::Void dateTimePicker1_ValueChanged(System::Object^ sender, System::EventArgs^ e) {
}
I tried so many things but no matter what I did I could not make Text->
which is the command to place text in the TextBox
accept anything related to the DateTimePicker
.
2 Answers
Reset to default 0You can use standard databindings to bind the Value
property of a DateTimePicker to, in this case, the Text
property of a TextBox. No need to subscribe to any event.
Add this to stdafx.h
(or another include file you use for the same purpose):
#pragma once
#define nameof(_propname) #_propname
In the Form's Constructor (assuming the name assigned to the TextBox is Date_Text
):
Date_Text->DataBindings->Add(
nameof(Text),
dateTimePicker1,
nameof(Value),
true,
DataSourceUpdateMode::OnPropertyChanged
);
Formatting is set to true
, you have the same representation of, e.g., DateTime::Now.ToString()
, using the current System::Globalization::CultureInfo
The first event (Date_Text_TextChanged
) does not seem relevant. It is triggered when the context of the TextBox
itself changes, and you are would like to monitor changes in the DateTimePicker
.
For that the second event (dateTimePicker1_ValueChanged
) is the relevant one.
In order to update the TextBox
when the user selects a date in the DateTimePicker
, you need to modify it as following:
System::Void dateTimePicker1_ValueChanged(System::Object^ sender, System::EventArgs^ e)
{
// This assume the name of your `TextBox` is `Date_Text`,
// modify it if needed:
Date_Text->Text = dateTimePicker1->Value->ToString();
}
Note that the Value
property of the DateTimePicker
is of type DateTime
, and it supports various string representation formats that you can pass as argument to ToString()
. You can see more info about it here: Custom date and time format strings.