InvalidCastException error with clearing value of date picker - vb.net

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

Related

Pass datagridview values to message box with formatting in vb.net

I want to pass data from one formatted column in datagridview to message box but the problem is that the data is passed but the formatting is not included. I mean the column that I want to display is a numeric column when I pass the data, only the numbers is being passed. I want the comma and the period to be included.
Here is the image:
And here is the message box result:
As you can see there is no comma and period. I want to include the comma and period.
Here is the datagridview_cellformatting:
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
If (e.ColumnIndex = 7) Then
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ValueType = GetType(Double)
DataGridView1.Columns(7).DefaultCellStyle.Format = "N2"
End If
If DataGridView1.Rows(e.RowIndex).Cells(7).Value Is DBNull.Value Then
DataGridView1.Rows(e.RowIndex).Cells(7).Value = "0.00"
End If
End Sub
And here is the MessageBox:
MessageBox.Show(DataGridView1.Rows(0).Cells(7).Value)
How to solve this?
You are specifying the format for the column cells here:
DataGridView1.Columns(7).DefaultCellStyle.Format = "N2"
You need to provide that same format specifier when converting the value to a String anywhere else too, e.g.
MessageBox.Show(DataGridView1.Rows(0).Cells(7).Value.ToString(DataGridView1.Columns(7).DefaultCellStyle.Format))
If you were to have Option Strict On, which you ALWAYS should, then you'd need to do this:
MessageBox.Show(CDbl(DataGridView1.Rows(0).Cells(7).Value).ToString(DataGridView1.Columns(7).DefaultCellStyle.Format))

Adding a year to date in 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

Convert SQL Server BIT datatype to boolean VB.NET

I'm a little rusty on my VB.NET especially when converting to SQL. I thought I had a simple task of hiding 2 buttons unless a checkbox is checked. The checkbox is bound to a SQL Server column with a bit data type.
My code is as follows:
Private Sub CaseVehicleCollisionCheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CaseVehicleCollisionCheckBox1.CheckedChanged
Dim collision As System.Data.SqlTypes.SqlBinary
collision = CaseVehicleCollisionCheckBox1
If collision = True Then
btnVehicle1.Visible = True
btnVehicle2.Visible = True
ElseIf collision = False Then
btnVehicle1.Visible = False
btnVehicle2.Visible = False
End If
End Sub
I keep getting the error
Value of type 'System.Windows.Forms.CheckBox' cannot be converted to 'System.Data.SqlTypes.SqlBinary'
when trying to assign the checkbox to the variable.
I get the same error when trying to use System.Data.SqlTypes.SqlBoolean
The problem is you are casting a CheckBox control to a SQLBinary datatype and that isn't going to work.
I presume CaseVehicleCollisionCheckBox1 is the name of the CheckBox. You need to use the CheckBoxes Checked property, eg:
Dim collision As Boolean
collision = CaseVehicleCollisionCheckBox1.Checked
Use SqlBoolean instead of sqlBinary.
sqlBinary is the sql equivalent of an array of bytes.

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.

Listbox.selected index change variable assignment

Hi there
What is the correct way of assigning the selected index's value from a listbox to a variable? The user selects an item in a listbox and then the output changes depending on their selection.
I use:
variablename = listbox.text
in the listBox_SelectedIndexChanged event and this works.
When I use the button_click event I use:
variablename = listbox.selectedindex
But this does not work in the listbox_selectedindexchanged event.
Please could you let me know if it is okay to use it like I did above or if I will run into problems and why you cannot use the selectedindex method.
Thanks!
A. It sounds like your variable is a string, and yet you are trying to assign to it the value returned by the SelectedIndex Property, which is an integer.
B. If you are trying to retrieve the value of the item associated with the SelectedINdex of the Listbox, use the Index to return the Object itself (the listbox is a list of Objects, which are often, but not always, going to be strings).
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
'THIS retrieves the Object referenced by the SelectedIndex Property (Note that you can populate
'the list with types other than String, so it is not a guarantee that you will get a string
'return when using someone else's code!):
SelectedName = ListBox1.Items(ListBox1.SelectedIndex).ToString
MsgBox(SelectedName)
End Sub
THIS is a little more direct, using the SelectedItem Property:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
'This returns the SelectedItem more directly, by using the SelectedItem Property
'in the event handler for SelectedIndexChanged:
SelectedName = ListBox1.SelectedItem.ToString
MsgBox(SelectedName)
End Sub
Well it depends what you want to achieve from the listbox's selected item.
There are a couple of possible ways, let me try to explain some of these for your homework.
Suppose you have a data table with two columns, and their rows...
ID Title
_________________________
1 First item's title
2 Second item's title
3 Third item's title
And you bind this data table to your list box as,
ListBox1.DisplayMember = "ID";
ListBox1.ValueMember = "Title";
If user selects second item from the list box.
Now if you want to get the display value (Title) of the selected item, then you can do
string displayValue = ListBox1.Text; // displayValue = Second item's title
OR even this to get same results.
// displayValue = Second item's title
string displayValue = ListBox1.SelectedItem.ToString();
And to get the value member against the selected item, you need to do
string selectedValue = ListBox1.SelectedValue; // selectedValue = 2
Now there are situations when you want to allow user to select more than one item from the list box, so you then set
ListBox1.SelectionMode = SelectionMode.MultiSimple;
OR
ListBox1.SelectionMode = SelectionMode.MultiExtended;
Now suppose if user selects two items; second and third.
So you can get the display values by simply iterating through the SelectedItems
string displayValues = string.Empty;
foreach (object selection in ListBox1.SelectedItems)
{
displayValues += selection.ToString() + ",";
}
// so displayValues = Second item's title, Third item's title,
And if you want to get ID's instead of Title's then...
I am also looking through it, I will post if found.
I hope your understandings build.
Good Luck!