Everytime no changes with method haschanges() - vb.net

I'm using a TableAdapter for a simple software in visual basic.
I entered a query -Search by name- but i want check for changes before start the search (because i'll lost the changes with the search).
My idea is this:
If TimeBankDataSet.HasChanges() Then
Try
Select Case MsgBox("Save the canges before searching?", MsgBoxStyle.YesNoCancel)
Case MsgBoxResult.Yes
Me.Validate()
Me.PeopleBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.TimeBankDataSet)
MsgBox("Saved", MsgBoxStyle.Information, "Info")
Exit Sub
Case MsgBoxResult.Cancel
Exit Sub
End Select
Catch ex As Exception
End Try
End If
But there are never changes..
Solved adding: Me.PeopleBindingSource.EndEdit()

Related

How to link TextBox data and DataGridView and save it in the MS Access database

I'm new to programming and I'm trying to make a simple information system. I've tried many codes and I think this is the easiest but it won't save the data. Please point out what I need to do. Thanks in advance.
Here is my code (for the save button):
If Len(Trim(txtStudentID.Text)) = 0 then
MessageBox.Show ("Please input data",MessageBoxButtons.OK,MessageBoxIcon.Error)
txtStudentID.Focus()
Exit Sub
End If
Try
GeneralInformationBindingSource.EndEdit()
GeneralInformationTableAdapter.Update(PayrollDatabaseSet.GeneralInformation)
MessageBox.Show (" Data Saved")
Catch ex As Exception
MessageBox.Show ("Error while Saving Data")
End Try

How to get the same query results displayed in both MS visual studio and listbox?

I was trying to run a search query to give me all records specified in the where clause in ms management studio with the desired result. However when I transferred that query into my vb project there was only one record displayed on the listbox.
Sql query in ms management studio:
select * from tblInwardFile where org_name = 'MSW' and in_file_date_recieved like '05-Jun-19'
Below is my vb project:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
lstUpload.Items.Clear()
Try
cm = New SqlCommand("select * from tblInwardFile where org_name = 'MSW' and in_file_date_recieved like '05-Jun-19'", cn)
dr.Close()
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
lst = lstUpload.Items.Add(dr.Item(0))
lst.SubItems.Add(dr.Item(1))
lst.SubItems.Add(dr.Item(2))
lst.SubItems.Add(dr.Item(3))
lst.SubItems.Add(dr.Item(4))
lst.SubItems.Add(dr.Item(6))
Else
MessageBox.Show("File not found", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning)
dr.Close()
viewUploaded()
lowColor()
End If
'dr.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I would expect to see all records for the same query are displayed in the listbox. This is a query result in ms managment studio
Calling Read and then testing HasRows makes no sense at all. Here's how you should use those two members:
If there will never be more than one row, just call Read. If it returns True then there is data to read and if it returns False then there is no data. You only need an Else block if you want to do something specific if there is no data, e.g. notify the user.
If myDataReader.Read() Then
'Read data here.
End If
If myOtherDataReader.Read() Then
'Read data here.
Else
'There is not data.
End If
If there could be more than one row then you should use a Do or While loop and use the result of Read as the termination condition. As long as it is True, there is data to read, so terminate when it is False.
While myDataReader.Read()
'Read data here.
End While
2A. If there could be more than one row and you want to do something specific if there is none, e.g. notify the user, use an If...Else block to test HasRows and place your loop in the If block.
If myDataReader.HasRows Then
Do While myDataReader.Read()
'Read data here.
Loop
Else
'There is no data.
End If

Wait for a specefic program to open before continue VB.NET

Alright, as you see in the code down below I've got a simple try statement.
Whenever I open the tool it will look for a process named csgo, if there is a process it will continue with the tool else it will just send a MsgBox and exit the tool.
However, I want it for it to check if there is a csgo process running, if it's running it should continue like it is now, but if there isn't a process named csgo running I'd like to make the tool Sleep and loop til it finds a process named csgo.
Try
gameProcess = Process.GetProcessesByName("csgo")(0)
gameHandle = OpenProcess(PROCESS_ALL_ACCESS, False, csgoProcess.Id)
Catch ex As Exception
MsgBox("Please Start CS:GO before opening this tool")
Environment.Exit(0)
End Try
I tried doing like this, and it works lol, is there a better way of doing this?
Dim Found = 0
While Found = 0
Try
gameProcess = Process.GetProcessesByName("csgo")(0)
cgameHandle = OpenProcess(PROCESS_ALL_ACCESS, False, csgoProcess.Id)
Found = 1
Catch ex As Exception
MsgBox("Waiting for csgo to launch.")
Threading.Thread.Sleep(1000)
End Try
End While
Assuming this is a console application, you can make some improvements over what you have.
' Use a boolean for binary logic.
' This takes up 1 bit whereas your Int32 took up 32 bits
Dim allDone = False
While Not allDone
Try
Dim processes = Process.GetProcessesByName("csgo")
If processes.Count > 0 Then
csgoProcess = processes(0)
Dim handle = OpenProcess(PROCESS_ALL_ACCESS, False, csgoProcess.Id)
If handle IsNot Nothing Then
allDone = True
End If
Else
' Use a Retry / Cancel MsgBox to allow the user to retry or cancel
' Clicking Cancel will now exit the application
Select Case MsgBox("Waiting for csgo to launch.",
MsgBoxStyle.RetryCancel, "Confirm retry")
Case MsgBoxResult.Retry
Threading.Thread.Sleep(1000)
Case MsgBoxResult.Cancel
Environment.Exit(0)
End Select
End If
Catch ex As Exception
' Something bad happened, but you don't know what exactly.
' You should exit, else it might keep happening
MsgBox("Your application encountered the following error and will now close: " _
& ex.Message)
Environment.Exit(0)
End Try
End While
' continue application

Is there a difference between MsgBox and MessageBox.Show?

Is there a difference between the following two?
msgbox()
messagebox.show()
Some tutorials use msgbox(), and some use the other, messagebox.show()---I see that both can have an editable style, but I was wondering: Why are there two?
Is it to accommodate older programmers (who have learnt on an older version of Visual Basic)?
So in that case, which one should I use in Visual Basic 2010 (Visual Studio 2010)?
MsgBox() is the same as Messagebox.Show().
It exists for VB6 programmers who are used to it.
There are no rules on which one to use, but since MsgBox simply ends up delegating to MessageBox, I personally would go directly with MessageBox.
Here is the source code for Msgbox. As you can see it doesn't do anything particularly interesting before calling MessageBox.Show.
<MethodImpl(MethodImplOptions.NoInlining), HostProtection(SecurityAction.LinkDemand, Resources:=HostProtectionResource.UI)> _
Public Shared Function MsgBox(ByVal Prompt As Object, ByVal Optional Buttons As MsgBoxStyle = 0, ByVal Optional Title As Object = new Object()) As MsgBoxResult
Dim owner As IWin32Window = Nothing
Dim text As String = Nothing
Dim titleFromAssembly As String
Dim vBHost As IVbHost = HostServices.VBHost
If (Not vBHost Is Nothing) Then
owner = vBHost.GetParentWindow
End If
If ((((Buttons And 15) > MsgBoxStyle.RetryCancel) OrElse ((Buttons And 240) > MsgBoxStyle.Information)) OrElse ((Buttons And &HF00) > MsgBoxStyle.DefaultButton3)) Then
Buttons = MsgBoxStyle.OkOnly
End If
Try
If (Not Prompt Is Nothing) Then
[text] = CStr(Conversions.ChangeType(Prompt, GetType(String)))
End If
Catch exception As StackOverflowException
Throw exception
Catch exception2 As OutOfMemoryException
Throw exception2
Catch exception3 As ThreadAbortException
Throw exception3
Catch exception9 As Exception
Throw New ArgumentException(Utils.GetResourceString("Argument_InvalidValueType2", New String() { "Prompt", "String" }))
End Try
Try
If (Title Is Nothing) Then
If (vBHost Is Nothing) Then
titleFromAssembly = Interaction.GetTitleFromAssembly(Assembly.GetCallingAssembly)
Else
titleFromAssembly = vBHost.GetWindowTitle
End If
Else
titleFromAssembly = Conversions.ToString(Title)
End If
Catch exception4 As StackOverflowException
Throw exception4
Catch exception5 As OutOfMemoryException
Throw exception5
Catch exception6 As ThreadAbortException
Throw exception6
Catch exception13 As Exception
Throw New ArgumentException(Utils.GetResourceString("Argument_InvalidValueType2", New String() { "Title", "String" }))
End Try
Return DirectCast(MessageBox.Show(owner, [text], titleFromAssembly, (DirectCast(Buttons, MessageBoxButtons) And DirectCast(15, MessageBoxButtons)), (DirectCast(Buttons, MessageBoxIcon) And DirectCast(240, MessageBoxIcon)), (DirectCast(Buttons, MessageBoxDefaultButton) And DirectCast(&HF00, MessageBoxDefaultButton)), (DirectCast(Buttons, MessageBoxOptions) And DirectCast(-4096, MessageBoxOptions))), MsgBoxResult)
End Function
There is a difference when you are attempting to mix icons with different buttons. MsgBox has predefined styles (there may be a way to create new styles).
For example:
MsgBox("Do you wish to save changes?", MsgBoxStyle.YesNoCancel, "Save Changes")
^ This will display a box with Yes, No and Cancel buttons without an icon.
MsgBox("Do you wish to save changes?", MsgBoxStyle.Question, "Save Changes")
^ This will display a box with a Question mark icon but with ONLY an OK button.
MessageBox.Show("Do you wish to save changes?", "Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
^ This will display a box with Yes, No and Cancel buttons AND a Question mark icon.
As you can see, using MessageBox.Show enables you to have any buttons you want with any icon.
But the really nice thing about MsgBox is that it can be SystemModal e.g. If MsgBox("There is a new Quick Message!" & Environment.NewLine & "Do you want to read it now?", MsgBoxStyle.Information + MsgBoxStyle.YesNo + MsgBoxStyle.SystemModal, "Quick Message") = MsgBoxResult.Yes Then...
I couldn't find a simple way of making If MessageBox.Show(... to be SystemModal.
My messages now get full prominence on screen. Yippee.
According to this site and the answers so far to my own question (see remark), as well my inability to display a specific help file using the msgbox function, I'd have to say use messagebox rather than msgbox if you want to show help. The msgbox function displays a help button, but apparently there is no way to put a helpfile in it! I'm showing the code I played around with below, and there is also a good code sample on the first link.
Imports Microsoft.visualbasic 'have to have this namespace to use msgbox
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Helpfilepath As String = "C:\Windows\Help\mui\0409\aclui.chm"
Dim msgresult As Byte
'BTW, Must use 0 for BLANK PARAMETER. Using messageboxoptions.defaultdesktoponly errors out with help btn.
msgresult = MessageBox.Show("Text", "Messagebox", 0, _
0, 0, 0, Helpfilepath)
'displays help button, but how do you display the help file?
msgresult = MsgBox("Text", MsgBoxStyle.MsgBoxHelp, "msgbox")
'BTW, must use dialogresult rather than messageboxresult with windows forms
If msgresult = DialogResult.Yes Then
'etc
End If
End Sub
End Class
The message box created using MsgBox() has a title of the form which created it, whereas the message box window created by MessageBox.Show() does not have any title.

Error that can't be fixed?

I'm getting an error in my VB.NET application that connects to my SQL database. It connects fine, but for some reason I can't fix this error. When I try to fix it, it moves from one part of my script to another part of my script (both of which were working yesterday). The error details are:
Unfortunately, it's difficult for me to describe how I produced this result, because it has happened in multiple parts of my code, and the only thing that these parts have in common is their interaction with Listbox1.
The first part of code to get this error was:
Dim sqlpage As MySqlCommand = New MySqlCommand("SELECT * FROM [" & frmMain.ListBox1.SelectedItem.value & "]", con)
Then I got the same exact error for:
Private Sub ListBox1_SelectedValueChanged( _
ByVal sender As Object, ByVal e As System.EventArgs) _
Handles ListBox1.SelectedValueChanged
Try
Form1.Label1.Text = ListBox1.SelectedItem
Form1.Show()
Catch myerror As MySqlException
MessageBox.Show("Error Setting Up Project Page: " & myerror.Message)
End Try
End Sub
More specifically:
Form1.Label1.Text = ListBox1.SelectedItem
And then I got it a few more times, but I think the examples above will suffice.
Since there are no "With Block Variables" in the examples above then the only other option is that it's object related. I've tried different methods of defining and redefining the object variables related to the error. However, the results are the same.
In response to Juxtaposition's answer, my original problem has been solved however two new problems have come up specifically because I turned Option Strict on.
The first is:
Error1: Option Strict On disallows late binding.
The code in question is:
Try
' Retrieving the projects list.
con.Open()
DataAdapter2.SelectCommand = sqlprojects
DataAdapter2.Fill(ds2, "projects")
ListBox1.Items.Clear()
For Each DataRow In ds2.Tables("projects").Rows
' Error occurs on the line below
ListBox1.Items.Add(DataRow("project_name"))
Next
con.Close()
Catch myerror As MySqlException
MessageBox.Show("Error Retrieving Projects List: " & myerror.Message)
End Try
The second is:
Error 2: Option Strict On disallows implicit conversions from 'Object' to 'String'.
The code in question is:
Private Sub ListBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedValueChanged
Try
If ListBox1.SelectedItem IsNot Nothing Then
' Error occurs on the line below
Form1.Label1.Text = ListBox1.SelectedItem
End If
Form1.Show()
Catch myerror As MySqlException
MessageBox.Show("Error Setting Up Project Page: " & myerror.Message)
End Try
End Sub
It worked out... so I thank all of you for your time and patience.
You should always (99.999999% of the time) write VB.NET code with Option Strict On, unless you are writing interop code or interfacing with an esoteric database provider.
Simply place the words "Option Strict On" at the top of your file.
This will allow you to catch errors like the one you are dealing with.
Without Option Strict On you are allowed to write code like you have written:
Form1.Label1.Text = ListBox1.SelectedItem
The issue with that code is that is implicity tries to convert an object (ListBox1.SelectedItem) to a string (Form1.Label1.Text).
Turn option strict on and the compiler will give you an error up front.
You will then be forced to rewrite your code as such:
If ListBox1.SelectItem IsNot Nothing then
Form1.Label1.Text = ListBox1.SelectedItem
End If
Focus on this line for the moment:
Form1.Label1.Text = ListBox1.SelectedItem
If you're getting a NullReferenceException on this line, then one of the following has to be true:
Form1 is null
Form1.Label1 is null
ListBox1 is null
You can try to determine this by adding lines like these just before the above line:
Console.Writeline("Form1: " & (Form1 Is Nothing))
Console.Writeline("Form1.Label1: " & (Form1.Label1 Is Nothing))
Console.Writeline("ListBox1:" & (ListBox1 Is Nothing))
You should see a line that outputs true; that's the first clue. But then the next question is, why is it null? From what you've shown so far, I can't say.
Make sure ListBox1.SelectedItem is not Nothing in both of those circumstances.
Your original errors can be fixed without having to use Option Explicit On. You need to ensure that the Listbox.SelectedItem has a value before using it. The code should be written as:
If frmMain.ListBox1.SelectedItem IsNot Nothing Then
Dim sqlpage As MySqlCommand = New MySqlCommand("SELECT * FROM [" & frmMain.ListBox1.SelectedItem.value & "]", con)
End If
and
Try
If ListBox1.SelectedItem IsNot Nothing Then
Form1.Label1.Text = ListBox1.SelectedItem
End If
Form1.Show()
Catch myerror As MySqlException
MessageBox.Show("Error Setting Up Project Page: " & myerror.Message)
End Try
Update #2
Your second error should be fixed by changing the code to:
If ListBox1.SelectedItem IsNot Nothing Then
Form1.Label1.Text = ListBox1.SelectedItem.ToString
End If
Option Explicit On means that you have to explicitly convert data types.