I have a databound DateTimePicker:
dateDateTimePicker.DataBindings.Add(new Binding("Value", paymentBindingSource, "Date", true);
paymentBindingSource.DataSource = payment;
payment is Entity Framework object. payment.Date contains valid DateTime. When form is shown, dateDateTimePicker contains correct value, but an ErrorProvider is shown next to it, saying "Value of '01.01.0001 00:00:00' is not valid for 'Value'." It disappears when I change dateDateTimePicker value to anything.
Try reversing those two lines of code. The first line is probably looking to the data source, which, at that point, is null.
Would it be possible to see your validation code? I am guessing the validation error occurs when you first load the form, and that the way you bind the data does not clear the (existing) validation error, while when you manually change the value, that is triggering the relevant code.
Related
I have a drop-down menu in my web application that is data-bound to a DataTable. I want to make the first item in the drop-down list blank and be the first thing in the list. I am trying to do this by inserting a new DataRow where the text value is "" and the primary key value is DBNull.Value because I want the blank to raise an SQL exception if it is submitted. However if I try to insert this row I get a NoNullAllowedException.
I've tried myTable.PrimaryKey = null; and myTable.Constraints.Clear(); but no luck.
Is there a way around this? Or maybe even a better way to do this?
EDIT: for clarity I do understand that raising exceptions for validation is bad, and it's not for that. I want it to raise an exception in the case someone forgets to validate the input before sending it off to the database.
I have a basic app which contains a gridview with a sqldatasource. The datasource includes two date parameters. The params are linked to two textboxes which are prepopulated but can be modified by the user for their desired date range. I have two validation controls on each textbox. A requiredfieldvalidator and a comparefieldvalidator. The latter being a check for a valid date format.
When I (intentionally) break one of the dates, say, by adding a letter e.g 19/03/2014a (I'm in the U.K, date format is dd/mm/yy) the validation kicks in perfectly and it returns a message to say the date is invalid.
The issue:
Now at this point if I immediately select a row on the gridview, the app derails and I get an error: "Conversion failed when converting datetime from character string" This is expected given that I am using the dates in the textboxes as parameters for my gridview datasource and one of them now contains an invalid date. In an attempt to prevent the SelectedIndexChanged firing at all I have tried to handle the SelectedIndexChanging event for the gridview and cancel the row select. Here is the code for that:
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
Page.Validate();
if (!Page.IsValid)
{
e.Cancel = true;
return;
}
}
This codes "works" in that it prevents the SelectedIndexChanged event and also the gridview databind, BUT, I still get the same error: "Conversion failed when converting datetime from character string".
Can someone assist me with this please?
Help much appreciated as ever!
kind regards
Paul.
EDIT: Well I tried the suggestion of a regular expression. I removed other validators(both required and compare) The same error arises. No change.
What I don't understand is that when I cancel the the gridview selected index change event in "GridView1_SelectedIndexChanging" and the "GridView1_SelectedIndexChanged" does not fire, I would expect then that the page would be returned unchanged. But it totally derails and brings up the error. Why?! I'm cancelling the action!
When I step through the code with the invalid date entered, I can see that the gridview is not being databound there. Is it possibly attempting to DataBind() anyway?
Help appreciated greatly!
regards
Paul
EDIT: I finally solved this myself. I disabled automatic databinding and called DataBind() myself at the appropriate times. Another measure I thought of was to add validation login in the T-SQL so that invalid dates did not result in querying the db. There is likely to be a better solution but I couldn't find it and no one suggested it.
Removed Required field validator and go with Regular expression validator where you specify the regular expression of date and validate page against it.
Right now with required field validator its not firing validation because textbox has value but its not checking whether textbox has valid date or not.
See Regex to validate date format dd/mm/yyyy
I have a form with two data-bound text boxes, one data-bound DateTimePicker and a BindingNavigator. I bind these components at run-time to the relevant data sources (the 'Text' and 'Value' of the Text Boxes and DateTimePicker respectfully are bound the relevant fields in a data set). All the components display the present records correctly. Normally, when one clicks the "Add New Item" button on the navigator, all the Text Boxes will clear in preparation for the new entry. However, I have the problem that this does not occur when the DateTimePicker is bound, and furthermore any attempts to update the datasets do not occur correctly. If I neglect to bind the DateTimePicker then all works as expected. What is the cause of this behaviour and is there a way around it?
The DateTimePicker doesn't support binding to nullable data. When you add a new row, the value for that field will be DBNull.Value by default and that cannot be converted successfully to a value that can be assigned to the Value property of the DateTimePicker, which is type DateTime. You need to either extend the DateTimePicker and add a new property that supports both DateTime values and DBNull objects and bind that or else set the DefaultValue property of your DataColumn so that there will always be a DateTime to display in the DateTimePicker.
This problem was resolved for my scenario by simply controlling the addrow method of the binding source based on this site: http://www.vbforums.com/showthread.php?645401-RESOLVED-datetimepicker-with-binding-source
Add a new button on the binding navigator (to use as your 'Add') and remove the old one.
Connect to the click event and set the datetime of the new row being added:
DataRowView row = (DataRowView)bs_.AddNew();
row["dbDateTime"] = DateTime.Now;
where dbDateTime is your database field.
Although you may have to add some more code to the click event, such as moving to the newly added row on the datagrid, this option was by far the easiest to implement.
Situation: A C# Windows Forms application with a TextBox and a ComboBox. AutoValidate is set to EnableAllowFocusChange.
The TextBox represents and is shown as a percentage value e.g. "10 %" which is stored as an int. Both input controls are data bound, the TextBox with a parsing and formatting ConvertEventHandler as well as a Validating CancelEventHandler.
When entering an invalid input like "abc" and leaving the control: My Validation is performed and fails (e.Cancel = true, ErrorProvider ..). And my parsing fails (e.Value stays "abc").
Problem: When I now change the value of the ComboBox and leave it (lost focus/perform validation) or do a ValidateChildren, my format function is called with the last valid percentage value and the wrong input is lost.
Stacktrace: The problem is triggered by a ReportPropertyChanged of the ComboBox and leads to Binding.PushData, FormatObject and OnFormat -> Which calls my format function with the original value.
I want my TextBox to stay invalid and no magical reset. What can I do to prevent a value reset? Or what did I do wrong?
Thanks!
I'm updating a LINQ object prior to SubmitChanges. The values of the object's properties are being taken from a series of TextBoxes.
When I read in one specific TextBox, another TextBox changes its value with no apparent cause.
//...
loc.Lattitude = txtLocLat.Text; // txtLocLong.Text changes to previous value
loc.Longitude = txtLocLong.Text; // Which is now the previous value
dc.SubmitChanges();
// ...
As a result, loc.Longitude never gets updated with the user input. Why would it do this?
The TextBoxes have no databindings
The TextBoxes have no events defined
Breakpointing into the first line merely steps through the DataContext's loc.Lattitude setter.
Try putting a breakpoint on the txtLocLong TextChanged event and see if the stack trace is any help.