How to set null value to Datetimepicker when load? - vb.net

I have a Datetimepicker1, i want to set it to empty when load, and show value after chose.
I have found a code
Datetimepicker1.Format = DateTimePickerFormat.Custom
Datetimepicker1.CustomFormat = " "
but it does not show value after chose.

Try this
DateTime? dateSample= null;

DateTimePickers can't be set to null because DateTime can't be null, but you can set them to DateTime.MinValue which is the default value for an uninitialized DateTime. And then you just check if the dtp.Value = DateTime.MinValue and if so, treat it as null.
However, if you want to really distinguish when no value has been selected, the easiest way is to set DateTimePicker.ShowCheckBox to true, and then you check dtp.Checked and if it's true, you read the value, otherwise you treat it as a null.
Have you try this : for testing purpose
DateTime? myselectedDate = null;
private void DateTimePicker1_ValueChanged(Object sender, EventArgs e) {
myselectedDate = DateTimePicker1.Value;
}
And
this.dateTimePicker1.Format = DateTimePickerFormat.Custom;
this.dateTimePicker1.CustomFormat = " "; //a string with one whitespace

DatetimePicker can't have no value. Null or default value is DateTime.MinValue. Your code changes the format in order to show nothing.
To show the date again, simply change DateTimePicker.Format again when needed:
DateTimePicker1.Format = DateTimePickerFormat.Long;

Because , you formatted your datetimepicker "", you should write the below code in valuechanged event of the datetimepicker;
Datetimepicker1.Format = DateTimePickerFormat.short(type which you need short,long etc..)

Related

vb.net set cell numeric format after cellendedit event

I have predefined columns in my DataGridView.
There are two editable columns and one read-only column.
I have set all columns format to numeric style from cellstyle builder
When I input some text into the two columns, the format won't change, but the read-only column do.
So I've added format change on cellformatting event like this
Dim c As String
If e.ColumnIndex = colHrg.Index _
AndAlso e.Value IsNot Nothing AndAlso e.RowIndex >= 0 Then
c = e.Value.ToString
e.Value = c
End If
e.CellStyle.Format = "N3"
But it seems the event is not fired, so I decided to add format styling on cellendedit event.
Yet, it still didn't worked
dgv_beli.Columns("colHrg").DefaultCellStyle.Format = "N3"
I've also tried editingcontrolshowing and cellvaluechanged event, but still not working
Can someone guide me how to fixed this. I've spent a lot of time to solved this, really curious to find a good solution for my problem.
Add an event of EditingControlShowing
In EditingControlShowing, check that if the current cell lies in the desired column.
Register a new event of KeyPress in EditingControlShowing(if above condition is true).
Remove any KeyPress event added previously in EditingControlShowing.
In KeyPress event, check that if key is not digit then cancel the input.
Example:
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}

DateTime? Cannot assign a value

I need to have a property that is a nullable date as the datestamp is used for when a process is completed.
If there is no date this is a way to determain if the process has occured.
I have created a Nuallable DateTime property (DateTime?) however when i try to assign a value from my database entity(when debugged has a date value) i am not thrown an exception however my property still reads a null value after assignment.
How can i get a DateTime? type to accept a DateTime value? i thought this would do the trick _object.DateStamp (type = DateTime?) = _entity.DateStamp (Type = DateTime?, Value = DateTime) or for more understandable syntax
Ctype(object.DateStamp, DateTime?) = Ctype(entity.DateStamp, DateTime?)
Strange thing is i can assign the properties value like this.
Ctype(object.DateStamp, DateTime?) = Now
Oh btw im uisng LinQ Entities.
Any Help?
I had this same problem. I would assign a date from a user entered value and it would never assign to the Nullable Date property on my custom object. My solution was to assign the user entered value into a local Nullable date variable, and then assign that value to the property. Trying to cast the user entered value into a nullable type on a single line didn't work for me either. The solution that worked for me is below:
Dim MyDate As Date? = Date.Parse(Me.txtDate.Text.Trim())
MyObject.Date1 = AppearanceDateAlternate
Another way this can burn you is if you try to use the "<>" operator on a mixture of null and not-null.
Public Property OwnerSignoffDate As Date?
Get
Return _ownerSignoffDate
End Get
Set(value As Date?)
If value <> _ownerSignoffDate Then 'BAD!
_ownerSignoffDate = value
Dirty = True
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("OwnerSignoffDate"))
End If
End Set
End Property
change to:
Public Property OwnerSignoffDate As Date?
Get
Return _ownerSignoffDate
End Get
Set(value As Date?)
If value <> _ownerSignoffDate OrElse value.HasValue <> _ownerSignoffDate.HasValue Then 'GOOD!
_ownerSignoffDate = value
Dirty = True
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("OwnerSignoffDate"))
End If
End Set
End Property

Why can't I check if a 'DateTime' is 'Nothing'?

In VB.NET, is there a way to set a DateTime variable to "not set"? And why is it possible to set a DateTime to Nothing, but not possible to check if it is Nothing? For example:
Dim d As DateTime = Nothing
Dim boolNotSet As Boolean = d Is Nothing
The second statement throws this error:
'Is' operator does not accept operands of type 'Date'. Operands must be reference or
nullable types.
This is one of the biggest sources of confusion with VB.Net, IMO.
Nothing in VB.Net is the equivalent of default(T) in C#: the default value for the given type.
For value types, this is essentially the equivalent of 'zero': 0 for Integer, False for Boolean, DateTime.MinValue for DateTime, ...
For reference types, it is the null value (a reference that refers to, well, nothing).
The statement d Is Nothing is therefore equivalent to d Is DateTime.MinValue, which obviously does not compile.
Solutions: as others have said
Either use DateTime? (i.e. Nullable(Of DateTime)). This is my preferred solution.
Or use d = DateTime.MinValue or equivalently d = Nothing
In the context of the original code, you could use:
Dim d As DateTime? = Nothing
Dim boolNotSet As Boolean = Not d.HasValue
A more comprehensive explanation can be found on Anthony D. Green's blog
DateTime is a value type, which is why it can't be null. You can check for it to be equal to DateTime.MinValue, or you can use Nullable(Of DateTime) instead.
VB sometimes "helpfully" makes you think it's doing something it's not. When it lets you set a Date to Nothing, it's really setting it to some other value, maybe MinValue.
See this question for an extensive discussion of value types vs. reference types.
DateTime is a value type, which means it always has some value.
It's like an integer - it can be 0, or 1, or less than zero, but it can never be "nothing".
If you want a DateTime that can take the value Nothing, use a Nullable DateTime.
Some examples on working with nullable DateTime values.
(See Nullable Value Types (Visual Basic) for more.)
'
' An ordinary DateTime declaration. It is *not* nullable. Setting it to
' 'Nothing' actually results in a non-null value.
'
Dim d1 As DateTime = Nothing
Console.WriteLine(String.Format("d1 = [{0}]\n", d1))
' Output: d1 = [1/1/0001 12:00:00 AM]
' Console.WriteLine(String.Format("d1 is Nothing? [{0}]\n", (d1 Is Nothing)))
'
' Compilation error on above expression '(d1 Is Nothing)':
'
' 'Is' operator does not accept operands of type 'Date'.
' Operands must be reference or nullable types.
'
' Three different but equivalent ways to declare a DateTime
' nullable:
'
Dim d2? As DateTime = Nothing
Console.WriteLine(String.Format("d2 = [{0}][{1}]\n", d2, (d2 Is Nothing)))
' Output: d2 = [][True]
Dim d3 As DateTime? = Nothing
Console.WriteLine(String.Format("d3 = [{0}][{1}]\n", d3, (d3 Is Nothing)))
' Output: d3 = [][True]
Dim d4 As Nullable(Of DateTime) = Nothing
Console.WriteLine(String.Format("d4 = [{0}][{1}]\n", d4, (d4 Is Nothing)))
' Output: d4 = [][True]
Also, on how to check whether a variable is null (from Nothing (Visual Basic)):
When checking whether a reference (or nullable value type) variable is null, do not use = Nothing or <> Nothing. Always use Is Nothing or IsNot Nothing.
In any programming language, be careful when using Nulls. The example above shows another issue. If you use a type of Nullable, that means that the variables instantiated from that type can hold the value System.DBNull.Value; not that it has changed the interpretation of setting the value to default using "= Nothing" or that the Object of the value can now support a null reference. Just a warning... happy coding!
You could create a separate class containing a value type. An object created from such a class would be a reference type, which could be assigned Nothing. An example:
Public Class DateTimeNullable
Private _value As DateTime
'properties
Public Property Value() As DateTime
Get
Return _value
End Get
Set(ByVal value As DateTime)
_value = value
End Set
End Property
'constructors
Public Sub New()
Value = DateTime.MinValue
End Sub
Public Sub New(ByVal dt As DateTime)
Value = dt
End Sub
'overridables
Public Overrides Function ToString() As String
Return Value.ToString()
End Function
End Class
'in Main():
Dim dtn As DateTimeNullable = Nothing
Dim strTest1 As String = "Falied"
Dim strTest2 As String = "Failed"
If dtn Is Nothing Then strTest1 = "Succeeded"
dtn = New DateTimeNullable(DateTime.Now)
If dtn Is Nothing Then strTest2 = "Succeeded"
Console.WriteLine("test1: " & strTest1)
Console.WriteLine("test2: " & strTest2)
Console.WriteLine(".ToString() = " & dtn.ToString())
Console.WriteLine(".Value.ToString() = " & dtn.Value.ToString())
Console.ReadKey()
' Output:
'test1: Succeeded()
'test2: Failed()
'.ToString() = 4/10/2012 11:28:10 AM
'.Value.ToString() = 4/10/2012 11:28:10 AM
Then you could pick and choose overridables to make it do what you need. Lot of work - but if you really need it, you can do it.
You can also use below just simple to check:
If startDate <> Nothing Then
your logic
End If
It will check that the startDate variable of DateTime datatype is null or not.
You can check this like below :
if varDate = "#01/01/0001#" then
' blank date. do something.
else
' Date is not blank. Do some other thing
end if
A way around this would be to use Object datatype instead:
Private _myDate As Object
Private Property MyDate As Date
Get
If IsNothing(_myDate) Then Return Nothing
Return CDate(_myDate)
End Get
Set(value As Date)
If date = Nothing Then
_myDate = Nothing
Return
End If
_myDate = value
End Set
End Property
Then you can set the date to nothing like so:
MyDate = Nothing
Dim theDate As Date = MyDate
If theDate = Nothing Then
'date is nothing
End If

What are NULL values and how can I handle them in SQLite

What are NULL values ?
Sometimes when I try to assign a query to variable, I get error saying Type-Cast-Error.
txtMiddleName.Text = Reader.GetString(2)
How can I put it that if the value of the Middle is nothing then
txtMiddleName.Text = ""
(I already read the other post "Handling NULL Values in SQLite but couldn't figure out much")
Working on VS 2010 (VB.net)
EDIT 1:
This is the error Message I get
(Line 364 is the above mentioned code)
NULL means there is no assigned value to the field.
The blank value in the MiddleName in the third row of your table is an empty string not a NULL.
If your are expecting a NULL to be a value of an object you can check it before assign it to another.
In your example you have to check for DBNULL values like the following:
if (Reader.IsDBNull(2))
{
// Do something ..
}
else
{
// Do something else ..
}
If you are not sure of the type of the value you are trying to get, use the following:
Reader.GetValue(2).ToString()
I think you should check
if(dread[2] != DBNull)
//assign value
The error is occurring as its trying to transform the database null value to string
Check for null before assigning the value to the textbox
If(Not Reader.IsDBNull(2)) Then
txtMiddleName.Text = Reader.GetString(2)
End If
there a constant called DBNull.value that you can use in comparisons to determine if it is a null or an empty string, a string like "". If you use a strongly typed data adapter you can also use datatable.IsMiddleNameNull() function to see if it is null.
Simple recap:
"" != null
and
null != DBNull
To actually answer your question, you are probably getting a DBnull value when you are getting the string from the reader. So before calling getString you need to make sure the value is not DBNull.value and then call getstring.
Try this out. May this will help you.
Dim a As string
a = TextBox1.Text
If String.IsNullOrEmpty(TextBox1.Text) Then
MessageBox.Show("Please enter Your Middle name")
Else
MessageBox.Show("your Middle name is " & a)
End If

How to stop DateTimePicker from showing Todays Date

Everytime when I start my program DateTimePicker automatically shows todays date and time. How can I stop this ? How can I make it blank ?
I have a DOB DateTimePicker. For some users I don't know their DOB so I would like the DateTimePicker to show null or empty field.
Set DateTimePicker.CustomFormat = " " Make sure there is a space. This will show up as a blank space.
I used a DataRowView drv = DBBindingSource(DB). along with a control statement to set null when needed.
if(drv.Row["DOB"] == DBNull.Value)
{
DateTimePicker.CustomFormat = " ";
}
else
{
DateTimePicker.CustomFormat = "dd MMMM yyyy";
}
I don't think there is a way to allow it to be blank but you could use the ShowCheckBox and Checked properties set to true. The DateTimePicker will then have a checkbox in addition to the date dropdown. The date dropdown is disabled when not checked. This allows you to have a 'no value' or null for the DOB when the checkbox is not checked.
See this CodeProject article on a Nullable DateTimePicker. It inhertis from DateTimePicker.
Use this :
Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged
DateTimePicker1.Value = DateTimePicker1.Value.Today
End Sub
Set it's Value property to the date you want.
if you are talking about datetimepicker from Trent Richardson, have a look at this thread
https://stackoverflow.com/a/12645192/551811
basically, set the inputbox value in the onClose event.
$('input.datetime').datetimepicker({
onClose: function (value) {
$('input.datetime').val(value);
}
});
my solution:
Public Sub ClearDatePicker(ByVal DatePicker As DateTimePicker)
DatePicker.CustomFormat = " "
DatePicker.Format = DateTimePickerFormat.Custom
End Sub
then the datetimepicker will be displayed empty.