LuckyLuke82 LuckyLuke82 - 3 months ago 8
Vb.net Question

Save only If changes made

I have a Save button on my form to save data to DB, and I want to create a short code for "not saving anything" If user doesn't make changes, because saving involves a lot of Textbox/Combobox/DateTimePicker values.

In other words, is there any different solution that I could use, rather than like this:

Using con As OracleConnection = New OracleConnection("Data Source=MyDB;User Id=Lucky;Password=MyPassword;")

con.Open()

Using cmd As OracleCommand = New OracleCommand()

Const SQL As String = "INSERT INTO MYTable (Field1,Field2,Field3 etc.) VALUES(: example1, : example2,: example3, etc.)"

cmd.Connection = con
cmd.Parameters.Add(New OracleParameter(": example1",Textbox1.Text ))
cmd.Parameters.Add(New OracleParameter(": example2",Textbox2.Text ))
cmd.Parameters.Add(New OracleParameter(": example3",Textbox3.Text ))

cmd.CommandText = SQL

If Textbox1.text="" And Textbox2.text="" And Textbox3.text="" Then
'Do nothing
Else
cmd.ExecuteNonQuery()
MessageBox.Show("Saved successfully")
End if

End Using

End Using


Currently my code saves to DB, even If textboxes are blank - so probably empty strings are inserted.

Answer

First of all you can simplyfy your code

If Textbox1.text="" And Textbox2.text="" And Textbox3.text="" Then
  'Do nothing
  Else
  cmd.ExecuteNonQuery()
  MessageBox.Show("Saved successfully")
End if

If Not (Textbox1.text="" And Textbox2.text="" And Textbox3.text="") Then 
      cmd.ExecuteNonQuery()
      MessageBox.Show("Saved successfully")
End if

or else

If Textbox1.text="" And Textbox2.text="" And Textbox3.text="" Then Exit Sub
cmd.ExecuteNonQuery()
MessageBox.Show("Saved successfully")

One possible way to solve the rest are events + a flag. Give every control a listener (Textchanged, ValueChanged, ..depending on the control). If it fires set a Flag Changes made from default False to True

In the end Check if Changes made is True - If yes, then save it to DB.

Negative: If the User puts some text and removes it afterwards the flag will still be true - But you can see this behaviour in many applications.