Reputation: 623
I have a TextBox where there is a date. I convert the date with the following line of code:
txtTextbox.Text = Convert.ToDateTime(txtTextbox.Text).ToString("dd/MM/yyyy");
The text in the textbox is now "05/12/1978".
But when I click inside the textbox to edit the date but I change my mind and I leave the textbox, the text is as follows: "05/12/1978 0:00:00".
I tried to fix this by converting the date in the txtTextbox_Leave
event but that doesn’t work.
EDIT:
private void Form1_Load(object sender, EventArgs e)
{
// TableAdapters
tblWerknemersTA = new dtsGIPTableAdapters.tblWerknemersTableAdapter();
tblAfdelingenTA = new dtsGIPTableAdapters.tblAfdelingenTableAdapter();
// DataSet
dtsGIP = new dtsGIP();
tblWerknemersTA.Fill(dtsGIP.tblWerknemers);
tblAfdelingenTA.Fill(dtsGIP.tblAfdelingen);
// DataView
dtvWerknemers = dtsGIP.tblWerknemers.DefaultView;
dtvWerknemers.Sort = "Familienaam ASC";
// BindingSource
tblWerknemersBS = new BindingSource();
tblWerknemersBS.DataMember = "tblWerknemers";
tblWerknemersBS.DataSource = dtvWerknemers;
// Databindings
textBox1.DataBindings.Add(new Binding("text", tblWerknemersBS, "Geboortedatum"));
// Convert date
textBox1.Text = Convert.ToDateTime(textBox1.Text).ToString("dd/MM/yyyy");
}
In this demo app I have two Textboxes, the problem occurs when I click on the first one and then on the second one.
EDIT 2:
private void Form1_Load(object sender, EventArgs e)
{
// TableAdapters
tblWerknemersTA = new dtsGIPTableAdapters.tblWerknemersTableAdapter();
tblAfdelingenTA = new dtsGIPTableAdapters.tblAfdelingenTableAdapter();
// DataSet
dtsGIP = new dtsGIP();
tblWerknemersTA.Fill(dtsGIP.tblWerknemers);
tblAfdelingenTA.Fill(dtsGIP.tblAfdelingen);
// DataView
dtvWerknemers = dtsGIP.tblWerknemers.DefaultView;
dtvWerknemers.Sort = "Familienaam ASC";
// BindingSource
tblWerknemersBS = new BindingSource();
tblWerknemersBS.DataMember = "tblWerknemers";
tblWerknemersBS.DataSource = dtvWerknemers;
// Databindings
Binding textBoxBinding = new Binding("text", tblWerknemersBS, "Geboortedatum");
textBoxBinding.FormatString = "dd/MM/yyyy";
textBox1.DataBindings.Add(textBoxBinding);
}
Upvotes: 2
Views: 106
Reputation: 14007
When you use data binding, it will update the control when the data changes. Unless you specify a specific format, it will use the default format for that. Setting the bound property to a specific value as you do is rather unusual, since you usually let the bound data determine the displayed value. In any case, you can not rely on a specific format that you use when you set the value (unless it matches the binding format).
The solution in your case is to set the binding format:
// Databindings
Binding textBoxBinding = new Binding("text", tblWerknemersBS, "Geboortedatum", true,
DataSourceUpdateMode.OnValidation, null, "d");
textBox1.DataBindings.Add(textBoxBinding);
Upvotes: 1