Adding a year to date in vb.net - vb.net

I have two DateTimePicker controls on a form.
How can I automatically add a year to the date I have selected in the 1st DateTimePicker and display it on the 2nd DateTimePicker? For example, if select a date 09/22/2017, then I want the 2nd DateTimePicker to display 09/22/2018.
Is this possible? If so, would you suggest some appropriate code? If not, would you suggest an alternative way to do it?

You can do it like this, using the DateTimePicker's ValueChanged event:
Private Sub DateTimePicker1_ValueChanged(Sender As DateTimePicker, e As EventArgs) Handles DateTimePicker1.ValueChanged
Me.DateTimePicker2.Value = Sender.Value.AddYears(1)
End Sub
To automatically generate this event handler code, double-click the first DateTimePicker control on your form.
You'll notice in this example that I've changed the casting of Sender from Object to DateTimePicker, so we can get IntelliSense in the IDE.

Not sure what exactly you need to do and what YEAR you're looking for, but the simple answer is:
SomeComboBox.text = Now.Year

If you are selecting a date then take the year from the datepicker.
Append it to the textbox below.
You can do it in this way.
year = dtp1.Value.Year
tb.Text = tb.text + year
This will just append the year when you change the datepicker however if you want tb.Text year to be replaced on every click of datepicker then you should do something like this.
Dim str as String = tb.Text 'Save current text
Dim arr as String() = str.Split(",")'Get previous text
currentYear = dtp1.Value.Year 'Get current year
tb.Text = arr(0) + currentYear 'Replace year in textbox with new year

Related

vb.net DatePicker not setting value when new date is selected

I'm working on a vb.net application (I'm very new to vb.net), and have just added a DatePicker to a field on a form- PostDate (the field was previously just a text box).
The date picker appears to work visually- when the user clicks inside the form field, the date picker calendar appears, and they can select a date from the current month, or switch months to select a date from another month. Once the user has selected a date, the calendar disappears, and the newly selected date is displayed in the field in the format mm/dd/yyyy.
However, while debugging my application, when I reach the UpdateButton_Click() function that is handling the updates to fields in the form (i.e. checking to see if any of their values have changed, and updating them in the database if they have), I see that in the line I have added to check for changes to the date field that I have just added the DatePicker to, the date variable still holds the previous value (i.e. the original date, rather than the newly selected date).
The UpdateButton_Click() function is defined with:
Protected Sub UpdateButton_Click(sender As Object, e As EventArgs) Handles UpdateButton.Click
If Page.IsPostBack Then
...
Dim mypostdate As String = HttpUtility.HtmlEncode(PostDate.Text & " " & theTime.Text)
...
C.updateCaseByCaseID(... mypostdate, ...)
...
Next
End If
End Sub
If I put a break point on this function, and step through it, I can see that the value of PostDate.Text is always its original value (i.e. it has a previously saved value when the page loads). Even if I change the value of the field to a new date, using the date picker, although the field shows the new date in the browser, when I step through this function, the value of PostDate.Text is always the original date value.
The call to C.updateCaseByCaseID(...) appears to be what is handling the database updates, and was originally defined in cases.vb with:
Public Function updateCaseByCaseID(ByVal Caseid As String, ...) As String
Dim con As New SqlConnection(connectionString)
Dim sql As String = "UPDATE tableName SET "
sql = sql & " ReportNumber=#ReportNumber, ... "
If status = "" Then
Else
sql = sql & " ,status=status "
End If
...
If PostDate = "" Then
Else
sql = sql & ", PostDate=#PostDate"
End If
' Other similar If Else statements for the other parameters '
...
Dim cmd As New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#CID", Cid)
...
cmd.Parameters.AddWithValue("#PostDate", PostDate)
' Other similar AddWithValue statements '
...
If state = "" Then
Else
cmd.Parameters.AddWithValue("#State", State)
End If
' Other similar If statements for the other parameters '
...
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Dim myaction As String = "Done"
Return myaction
End Function
I added the postdate parameter to the sql variable by changing that line to:
sql = sql & " ReportNumber=#ReportNumber, ..., PostDate=#PostDate, ...
However, although this does now update the value of the post date field, it appears to update it to today's date, rather than the date selected by the DatePicker. This seems to be because although the PostDate field displays the newly selected date in the browser, in the UpdateButton_Click(...) function, in the line
Dim mypostDate As String = HttpUtility.HtmlEncode(PostDate.Text + " " + theTime.Text)
the variable PostDate.Text, i.e. the form field that is displaying the newly selected date in the browser, appears to have the value of today's date... I don't understand why this is happening...? Surely it should contain the value of the date selected in the DatePicker? Especially given that that is what's being displayed in the browser...
Anyone have any suggestions what I'm doing wrong with this?
Edit
As mentioned in the comments, I have updated the UpdateButton_Click() function as follows:
Protected Sub UpdateButton_Click(sender As Object, e As EventArgs) Hanles UpdateButton.Click
If Page.IsPostBack Then
...
Dim mypostdate As String = HttpUtility.HtmlEncode(PostDateTxt.Text & " " & theTime.Text)
Dim postDateAndTimeParts = mypostdate.Split("/")
Dim postTime = postDateAndTimeParts(2).Split("/")
Dim postDay = postDateAndTimeParts(1)
Dim postMonth = postDateAndTimeParts(0)
Dim postYear = postDateAndTimeParts(2).Split(" ")(0)
Dim postHour = postTime.Split(":")(0)
Dim postMin = PostTime.Split(":")(1)
DateTime PostDate = New DateTime(postYear, postMonth, postDay, postHour, postMin, 0);
...
C.updateCaseByCaseID(...)
End If
End Sub
My intention is to pass the new PostDate DateTime object that I'm reconstructing from the String into the C.updateCaseByCaseId(...) call, however on the line where I'm constructing that object, I'm currently getting a compile error that says:
Method arguments must be enclosed in parentheses
I'm not sure why this is? I can't see where I'm missing any parentheses...

VB.net Using a string to change something.Text

I need to work in VB.net for school and have encountered a problem.
The program works like this:
I've got a store page with buttons to buy them, they each have a name with the item and "_buy" after it. So if I wanted to buy a laptop, I'd press a button named laptop_buy.
What I want then is to make the event call the fuction Buy(laptop), so I can use the laptop ID later on.
I also have things named like laptop_level and laptop_price. I want to change them when I click the button. So I created this function:
Private Sub laptop_buy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles laptop_buy.Click
Buy("laptop")
End Sub
And
Function Buy(ByVal item)
Dim itemlevel As String = item + "_level.Text"
itemlevel += 1
End Function
So this should change the laptop_level.Text when I click laptop_buy.
But it isn't working.
Help is greatly appriciated!
You can use ControlCollenction.Find method to get your label.
Then you need to cast it's text value to Integer (I recommend using Int32.TryParse method for that) and then add 1 and return the result to the label text. Something like this should do the trick.
Sub Buy(ByVal item As String)
Dim level As Inetger
Dim ItemLabel as Label;
Dim ChildControls As Control() = Me.Controls.Find(item & "_level", True)
If ChildControls.Length > 0 Then
ItemLabel = ChildControls(0)
End If
If not isNothing(ItemLabel) AndAlso Int32.TryParse(ItemLabel.Text, level) Then
ItemLabel.Text = (Level + 1).ToString
End If
End Sub
Note: Code was written directly here, and it's been a long time since my vb.net days, so there might be some mistakes in the code.
Your trying to add 1 to a string.
A 'String' is a series of text characters, so the '1' in your text box is the character '1' not the number. You need to first conver the text into an 'integer'
Try:
dim itemlevel as integer = TryCast(item, integer)
If IsNothing(itemlevel) = false then
itemlevel = itemlevel + 1
Return itemlevel
end if
MSDN TryCast

can I convert a label that shows the time into a background color?

I have a label that displays the time and I would like to convert that label.text into a color for the background that changes every time the time changes. Is this possible? My code is below.
Example:
If the time displayed is 11:23:04 I would like the background color to be changed to #112304.
If the time displayed is 11:24:00 I would like the background color to be changed to #112400.
etc. etc.
Private Sub Timer1_Tick() Handles Timer1.Tick
Label1.Text = TimeOfDay
Label2.Text = System.DateTime.Now.ToString("MM/d/yyy")
End Sub
It's possible to create a new color by using the FromArgb. The TimeOfDay property is a TimeSpan which contains a Hour, Minute and Second property.
Color.FromArgb(DateTime.TimeOfDay.Hour, DateTime.TimeOfDay.Minute, DateTime.TimeOfDay.Second)
This will use decimal, so 11:12:13 will be #0B0C0D if you want to use decimal format you'll need to convert it first.
First Remove the ":" from the time and then convert it into a hex color
Dim remove = Label1.Text.Replace(":", "")
Me.BackColor = ColorTranslator.FromHtml("#" & remove)
Combine Dmandy's ColorTranslator.FromHtml() approach and format the time as you've already demonstrated with ToString():
Me.BackColor = ColorTranslator.FromHtml(DateTime.Now.ToString("#HHmmss"))

InvalidCastException error with clearing value of date picker

I use code such as this to clear out the values in several text boxes:
Private Sub RibbonButtonInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RibbonButtonInsert.Click
UpdateDataSource()
StudentsBindingSource.ResetBindings(True)
DatePickerDateOfBirth.Value = ""
RichEditBoxForeName.Focus()
StudentsBindingSource.AddNew()
End Sub
Because the date picker control did not clear out like the other controls did, I tried:
DatePickerDateOfBirth.Value = ""
but it does not clear out. Instead, I get an "InvalidCastException".
Can you show me what coding I need to properly clear out the value in this data picker?
Actually you are not clearing it out, you are assigning a string value to it. and as it is a Date type, the assignment is wrong.
the assigned value must be a Date format, you can do this:
DatePickerDateOfBirth.Value = Date.MinValue
later you can check and if the value is equal to MinValue, then the date is not set.
You cant set DateTimePicker Value to null or empty string it's value must be a date
but you can but a checkbox in datetimepicker using ShowCheckBox Property
and then use dateTimePicker.Checked = false dateTimePicker.Checked

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.