Windows Form doesn't disable on Enabled = False - vb.net

I have these two subroutines which handle a button click event for two buttons on a form. Each one causes another smaller form to be displayed over the window which requires user input before the user may continue.
In both cases I have used Enabled = False to disable to main form while the smaller form is active. In the first Sub, AddNewPatientButton_Click, this has the desired effect of disabling the main form. However, for DeletePatientButton_Click, this has no effect.
Below is the code for the event handlers:
Private Sub AddNewPatientButton_Click(sender As Object, e As EventArgs) Handles AddNewPatientButton.Click
NewPatientForm.Show()
Enabled = False
End Sub
Private Sub DeletePatientButton_Click(sender As Object, e As EventArgs) Handles DeletePatientButton.Click
AreYouSureForm.Show()
Enabled = False
If AreYouSureForm.yesSelected Then
Dim sqlQuery As String = "DELETE FROM Patients WHERE "
Dim firstName As String = PatientDataGridView.CurrentRow.Cells.Item(0).Value.ToString()
Dim lastName As String = PatientDataGridView.CurrentRow.Cells.Item(1).Value.ToString()
Dim dOB As String = PatientDataGridView.CurrentRow.Cells.Item(2).Value.ToString()
dOB = dOB.Substring(0, 2) & dOB.Substring(3, 2) & dOB.Substring(6, 4)
sqlQuery = sqlQuery & "Firstname = '" & firstName & "' AND Surname = '" & lastName & "' AND DateOfBirth = '" & dOB & "'"
DatabaseModule.AddOrDelete(sqlQuery, True, True)
End If
Enabled = True
End Sub
And here is the code for the NewPatientForm that the first event brings up:
Public Class NewPatientForm
Private Sub NewPatientForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Populate the year drop-down box with all of the years between now and 1900
Dim year As Integer = Date.Today.Year()
Do Until year = 1899
YearComboBox.Items.Add(year)
year -= 1
Loop
End Sub
Private Sub CancelAddButton_Click(sender As Object, e As EventArgs) Handles CancelAddButton.Click
PatientDatabaseForm.Enabled = True
Me.Close()
End Sub
Private Sub OkayButton_Click(sender As Object, e As EventArgs) Handles OkayButton.Click
Dim sqlQuery As String = "INSERT INTO Patients (Firstname, Surname, DateOfBirth) VALUES ("
'Get inputs
Dim firstName As String = FirstNameTextBox.Text
Dim surname As String = LastNameTextBox.Text
Dim dOB As String = DayComboBox.Text & "-" & MonthComboBox.Text & "-" & YearComboBox.Text
'Build sql insert string from inputted values
If (firstName <> "") And (surname <> "") And (dOB <> "--") Then 'If no input, then display message
sqlQuery = sqlQuery & "'" & firstName & "', "
sqlQuery = sqlQuery & "'" & surname & "', "
sqlQuery = sqlQuery & "'" & dOB & "')"
DatabaseModule.AddOrDelete(sqlQuery, True, False)
Else
MessageBox.Show("Invalid input")
End If
End Sub
End Class
And the code for the AreYouSureForm that the second event brings up:
Public Class AreYouSureForm
Public yesSelected As Boolean
Public Sub YesButton_Click(sender As Object, e As EventArgs) Handles YesButton.Click
yesSelected = True
Close()
End Sub
Private Sub NoButton_Click(sender As Object, e As EventArgs) Handles NoButton.Click
yesSelected = False
Close()
End Sub
End Class
I'm probably just missing something really stupid, but I can't see it :(
Any help would be appreciated, thanks

Related

Visual Studio 2010 - Message Box popping up twice, why and how to fix?

I'm writing a small app that allows the user to return and update three types of labels based on searching by charting number, order number, or product ID. How the design works is that there is an input box where you input the either the charting number/order number/product id and specify by selecting one of three radio buttons corresponding to the above three choices for input. There are three boxes to the right of the input box that returns the label IDs of each type of label, and the contents of these box can be directly edited and updated by clicking on an update button. The problem is that the return message pops up twice after updating, which is a nuisance, so I was wondering where in my code should I change to resolve this issue? I will paste the full code below in case the problem is located somewhere I haven't expected:
Imports MySql.Data.MySqlClient
Public Class Form1
Dim dbconn As New MySqlConnection
Dim sql As String
Dim mycommand As New MySqlCommand
Dim mydata As MySqlDataReader
Public Sub myConnection()
dbconn = New MySqlConnection("Server=###;Database=###;Uid=###;Pwd=###;")
Try
dbconn.Open()
Catch ex As Exception
MsgBox("Connection Error: " & ex.Message.ToString)
End Try
End Sub
Private Sub chartNoSub()
myConnection()
sql = "SELECT pltlbl, cuslbl, boxlbl from formats as a join ordtab as b join chart as c where a.prodid=b.cusled and concat(b.ordno, b.orditm)=concat(c.ord01, c.oitm01) and c.chart='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mydata = mycommand.ExecuteReader
While (mydata.Read())
pltLBL.Text = mydata.Item("pltlbl")
cusLBL.Text = mydata.Item("cuslbl")
boxLBL.Text = mydata.Item("boxlbl")
End While
mydata.Close()
dbconn.Close()
End Sub
Private Sub ordNoSub()
myConnection()
sql = "SELECT pltlbl, cuslbl, boxlbl from formats as a join ordtab as b where a.prodid=b.cusled and concat(b.ordno, '-', b.orditm)='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mydata = mycommand.ExecuteReader
While (mydata.Read())
pltLBL.Text = mydata.Item("pltlbl")
cusLBL.Text = mydata.Item("cuslbl")
boxLBL.Text = mydata.Item("boxlbl")
End While
mydata.Close()
dbconn.Close()
End Sub
Private Sub prodIDsub()
myConnection()
sql = "select pltlbl, cuslbl, boxlbl from formats where prodid='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mydata = mycommand.ExecuteReader
While (mydata.Read())
pltLBL.Text = mydata.Item("pltlbl")
cusLBL.Text = mydata.Item("cuslbl")
boxLBL.Text = mydata.Item("boxlbl")
End While
mydata.Close()
dbconn.Close()
End Sub
Private Sub Input_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles inputBox.TextChanged
pltLBL.Clear()
cusLBL.Clear()
boxLBL.Clear()
If (inputBox.Text <> "" And prodID.Checked = False And ordNo.Checked = False And chart.Checked = False) Then MsgBox("Please select an option below before inputting.")
If prodID.Checked = True Then
prodIDsub()
End If
If ordNo.Checked = True Then
ordNoSub()
End If
If chart.Checked = True Then
chartNoSub()
End If
End Sub
Private Sub update_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles updateLBL.Click, updateLBL.Click
myConnection()
sql = "update formats as a inner join ordtab as b on a.prodid = b.cusled inner join chart as c on b.ordno=c.ord01 and b.orditm=c.oitm01 set a.pltlbl = '" & pltLBL.Text & "', a.cuslbl = '" & cusLBL.Text & "', a.boxlbl = '" & boxLBL.Text & "' where a.prodid = '" & inputBox.Text & "' or concat(b.ordno, '-', b.orditm)='" & inputBox.Text & "' or c.chart='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mycommand.CommandType = CommandType.Text
Dim rows = mycommand.ExecuteNonQuery()
If rows <> 0 Then
MessageBox.Show("Update successful!")
Else
MessageBox.Show("Check input.")
End If
dbconn.Close()
End Sub
Private Sub clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clearLBL.Click
prodID.Checked = False
ordNo.Checked = False
chart.Checked = False
inputBox.Text() = ""
End Sub
End Class
Just to mark this as answered;
The solution was found, somewhat incredibly, by #GlorinOakenfoot.
The MsgBox was being called in Private Sub update_Click, but the Handles had the event happening twice on every click, hence the recursion of everything.

concurrency violation : Updated 0 of the expected 1 records

Can some one please assist me? How to get rid of this error?
concurrency violation : Updated 0 of the expected 1 records
I have been struggling with the update command for the last couple of days. I tried many solutions from the internet but I am unable to resolve this issue.
Imports Microsoft.Office
Imports System.Data.OleDb
Public Class Form1
Dim dt As New DataTable
Dim cnn As New OleDb.OleDbConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'filling analyst filter
Dim sText As String = String.Empty
Dim sConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\ecxx-store\Exxx xxxxsk\Txx Axxx\Enxx Flxxx\Source\Exx_Exxx_Flagging.accdb" 'Put your connection string in here
Using cn As New OleDb.OleDbConnection(sConnString)
cn.Open()
Dim cmd As New OleDb.OleDbCommand("SELECT Distinct Analyst FROM EF ORDER BY Analyst", cn)
Dim r As OleDb.OleDbDataReader = cmd.ExecuteReader()
While r.Read()
ComboBox7.Items.Add(r("analyst"))
End While
r.Close()
cn.Close()
End Using
'end of filling analyst filter
Me.EFTableAdapter.Fill(Me.Exx_Exxxx_ShippingDataset.EF)
Me.Label19.Text = "Welcome " & StrConv(Environment.MachineName, vbProperCase)
Me.Label20.Text = EFBindingSource.Count.ToString() & " entries"
'Setting Followup Status
Me.ComboBox8.Text = "Waiting for approval"
'disabling Second Analyst Details
Me.txtsecondanalyst.Enabled = False
Me.txtapproval.Enabled = False
Me.txtnotes.Enabled = False
End Sub
Private Sub txtdof_ValueChanged(sender As Object, e As EventArgs) Handles txtdof.ValueChanged
Me.txtnd.Text = DateDiff(DateInterval.Day, CDate(txtdof.Text), Now())
End Sub
Private Sub ComboBox7_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox7.SelectedIndexChanged
If IsNothing(Me.ComboBox8.Text) Then
EFBindingSource.Filter = "[Analyst] LIKE '%" & ComboBox7.Text & "%'"
Else
EFBindingSource.Filter = "[FollowupStatus] LIKE '%" & ComboBox8.Text & "%' AND [Analyst] Like '%" & ComboBox7.Text & "%'"
End If
'count of datagrid
Me.Label20.Text = EFBindingSource.Count.ToString() & " entries"
End Sub
Private Sub ComboBox8_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox8.SelectedIndexChanged
If IsNothing(Me.ComboBox7.Text) Then
EFBindingSource.Filter = "[FollowupStatus] LIKE '%" & ComboBox8.Text & "%'"
Else
EFBindingSource.Filter = "[FollowupStatus] LIKE '%" & ComboBox8.Text & "%' AND [Analyst] Like '%" & ComboBox7.Text & "%'"
End If
'count of datagrid
Me.Label20.Text = EFBindingSource.Count.ToString() & " entries"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'update
Me.txtnd.Visible = True
Me.txtnd.Text = DateDiff(DateInterval.Day, CDate(txtdof.Text), Now())
On Error GoTo SaveErr
EFBindingSource.EndEdit()
EFTableAdapter.Update(Exx_Exxxx_ShippingDataset.EF)
Me.txtsecondanalyst.Enabled = False
Me.txtapproval.Enabled = False
Me.txtnotes.Enabled = False
MsgBox("Record Updated or Saved")
SaveErr:
End Sub
Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
EFBindingSource.EndEdit()
Me.TableAdapterManager1.UpdateAll(Me.Exx_Exxx_ShippingDataset)
End Sub
End Class
According to Concurrency violation: the UpdateCommand affected 0 of the expected 1 records. DB concurrencyException was unhandled
You call
Me.EFTableAdapter.Fill(Me.Exx_Exxxx_ShippingDataset.EF)
in Form_Load, but there is no guarantee that the rows aren't changed by the time you call
EFTableAdapter.Update(Exx_Exxxx_ShippingDataset.EF)
in Button1_Click
In the linked answer,
ADO.Net keeps the value of the column when it was selected from the database. When it performs the update the condition is that none of the columns have changed when you commit.
Perhaps you should call
dt = dt.GetChanges()
immediately before updating in Button1_Click, so that the datatable gets updated with the latest values in the database.

How to get a information from a listbox to textboxes with radio buttons

I have been trying to figure out what I am doing wrong. I have two radio buttons one for a new user a the other for an existing user. The new user radio button takes the information input into the textboxes and adds to the list box. The existing user button is supposed to take the line selected in the listbox and break it up then put it back into my textboxes. I have written code for the radio buttons but they are not working properly. How can I get the information to process correctly and show in the textboxes? I have tried a split and a function but this was unsuccessful. Can anyone help? This is what I have for the radio buttons so far I can post the rest of the code if you need me to.
Private Sub rbtnNew_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtnNew.CheckedChanged
lstCustomer.Items.Add(RevName(txtName.Text.ToUpper) & " , " & (txtAddress.Text.ToUpper) & " , " & (txtCity.Text.ToUpper))
End Sub
Private Sub rbtnExisting_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtnExisting.CheckedChanged
Dim name1 As String
Dim address2 As String
Dim city2 As String
Dim output() As String
name1 = txtName.Text
address2 = txtAddress.Text
city2 = txtCity.Text
output = Split(lstCustomer.SelectedItem.ToString(), ",")
txtName.Text = output(0)
txtAddress.Text = output(1)
txtCity.Text = output(2)
lstResults.Items.Clear()
txtChairs.Clear()
txtSofas.Clear()
End Sub
End Class
In this case, the radiobuttons are very difficult to manage when they have the AutoCheck property set to True. Anyway I give you a couple of possible solutions:
Solution #1 (AutoCheck property set to True):
Private Sub rbtnNew_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbtnNew.CheckedChanged
Static wasInvoked As Boolean
If Not wasInvoked Then
If rbtnNew.Checked Then
lstCustomer.Items.Add(RevName(txtName.Text.ToUpper) & " , " & (txtAddress.Text.ToUpper) & " , " & (txtCity.Text.ToUpper))
Else
If lstCustomer.SelectedItem Is Nothing Then
wasInvoked = True
rbtnNew.Checked = True
wasInvoked = False
MessageBox.Show("Please select a customer from the list.")
End If
End If
End If
End Sub
Private Sub rbtnExisting_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbtnExisting.CheckedChanged
If rbtnExisting.Checked Then
Dim name1 As String
Dim address2 As String
Dim city2 As String
Dim output() As String
name1 = txtName.Text
address2 = txtAddress.Text
city2 = txtCity.Text
output = Split(lstCustomer.SelectedItem.ToString(), ",")
txtName.Text = output(0)
txtAddress.Text = output(1)
txtCity.Text = output(2)
lstResults.Items.Clear()
txtChairs.Clear()
txtSofas.Clear()
End If
End Sub
Solution #2 (RadioButtons's AutoCheck property set to False):
Private Sub rbtnNew_CheckedChanged(sender As Object, e As System.EventArgs) Handles rbtnNew.CheckedChanged
rbtnExisting.Checked = Not rbtnNew.Checked
End Sub
Private Sub rbtnExisting_CheckedChanged(sender As Object, e As System.EventArgs) Handles rbtnExisting.CheckedChanged
rbtnNew.Checked = Not rbtnExisting.Checked
End Sub
Private Sub rbtnNew_Click(sender As Object, e As System.EventArgs) Handles rbtnNew.Click
If Not rbtnNew.Checked Then
rbtnNew.Checked = True
lstCustomer.Items.Add(RevName(txtName.Text.ToUpper) & " , " & (txtAddress.Text.ToUpper) & " , " & (txtCity.Text.ToUpper))
End If
End Sub
Private Sub rbtnExisting_Click(sender As Object, e As System.EventArgs) Handles rbtnExisting.Click
If Not rbtnExisting.Checked Then
If lstCustomer.SelectedItem Is Nothing Then
MessageBox.Show("Please select a customer from the list.")
Else
rbtnExisting.Checked = True
Dim name1 As String
Dim address2 As String
Dim city2 As String
Dim output() As String
name1 = txtName.Text
address2 = txtAddress.Text
city2 = txtCity.Text
output = Split(lstCustomer.SelectedItem.ToString(), ",")
txtName.Text = output(0)
txtAddress.Text = output(1)
txtCity.Text = output(2)
lstResults.Items.Clear()
txtChairs.Clear()
txtSofas.Clear()
End If
End If
The radiobutton checkedchanged event may be trigger either it is checked or unchecked. Make sure check the value/attribution of the radiobutton in the event function.
Edit: Do you have the error-checking code for the case that listbox has no items at all? Since no item is seleced in listbox will cause ListBox.SelectedItem return null or something which the Split() function can not handle.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditem%28v=vs.110%29.aspx
In addition, using the string manipulation function provided by the system, such as join(), concat().
http://msdn.microsoft.com/en-us/library/aa903372%28v=vs.71%29.aspx
Check the size/length of the resulting string array from split().

Updating data in gridview using vb.net

First I populated the datagridview by data of sqlserver 2008 database table, now i have muliple rows in datagridview containing data, i am trying to update any row but, in the database table it replaces other rows data by the row data that iam trying to update
the code for update statement is given below
Plz help me
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" &
dgvEmpDetail.Rows(0).Cells(1).Value & "', Experience ='" &
dgvEmpDetail.Rows(0).Cells(2).Value & "', Skills='" &
dgvEmpDetail.Rows(0).Cells(3).Value
& "' where Emp_ID = '" & dgvEmpDetail.Rows(0).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
You've hard coded the row - dgvEmpDetail.Rows(0).
I imagine you are calling this in a loop. You should do something like:
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" & dgvEmpDetail.Rows(i).Cells(1).Value & "', Experience ='" & dgvEmpDetail.Rows(i).Cells(2).Value & "', Skills='" & dgvEmpDetail.Rows(i).Cells(3).Value()& "' where Emp_ID = '" & dgvEmpDetail.Rows(i).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Next
Your code is susceptible to SQL injection. You should put the update SQL in to a stored procedure - its faster and safer!
Protected Sub Page_Load()
If Not Page.IsPostBack Then
' Create a new table.
Dim taskTable As New DataTable("TaskList")
' Create the columns.
taskTable.Columns.Add("Id", GetType(Integer))
taskTable.Columns.Add("Description", GetType(String))
taskTable.Columns.Add("IsComplete", GetType(Boolean))
'Add data to the new table.
For i = 0 To 19
Dim tableRow = taskTable.NewRow()
tableRow("Id") = i
tableRow("Description") = "Task " + i.ToString()
tableRow("IsComplete") = False
taskTable.Rows.Add(tableRow)
Next
'Persist the table in the Session object.
Session("TaskTable") = taskTable
'Bind data to the GridView control.
BindData()
End If
End Sub
Protected Sub TaskGridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
TaskGridView.PageIndex = e.NewPageIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
'Set the edit index.
TaskGridView.EditIndex = e.NewEditIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowCancelingEdit()
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Retrieve the table from the session object.
Dim dt = CType(Session("TaskTable"), DataTable)
'Update the values.
Dim row = TaskGridView.Rows(e.RowIndex)
dt.Rows(row.DataItemIndex)("Id") = (CType((row.Cells(1).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("Description") = (CType((row.Cells(2).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("IsComplete") = (CType((row.Cells(3).Controls(0)), CheckBox)).Checked
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Private Sub BindData()
TaskGridView.DataSource = Session("TaskTable")
TaskGridView.DataBind()
End Sub
</script>
I have a access connection with textbox as data feeder to database change it to SQL if u want. The code is:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form2
Dim conaccess As New OleDbConnection
Dim conreader As OleDbDataReader
Dim concmd As New OleDbCommand
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.EditMode = False
conaccess.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=d:\vijay.mdb"
conaccess.Open()
loadGrid()
End Sub
Private Sub loadGrid()
Dim access As String
access = "select * from vijay"
Dim DataTab As New DataTable
Dim DataAdap As New OleDbDataAdapter(access, conaccess)
DataAdap.Fill(DataTab)
DataGridView1.DataSource = DataTab
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
Dim no As String
no = "select Max(ID) from vijay"
Dim concmd As New OleDbCommand(no, conaccess)
conreader = concmd.ExecuteReader
If (conreader.Read) Then
If (IsDBNull(conreader(0))) Then
id_txt.Text = "1"
Else
id_txt.Text = conreader(0) + 1
End If
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End If
End Sub
Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Try
id_txt.Text = DataGridView1.Item(0, i).Value
name_txt.Text = DataGridView1.Item(1, i).Value
class_txt.Text = DataGridView1.Item(2, i).Value
gen_txt.Text = DataGridView1.Item(3, i).Value
branch_txt.Text = DataGridView1.Item(4, i).Value
age_txt.Text = DataGridView1.Item(5, i).Value
Catch ex As Exception
End Try
End Sub
Private Sub del_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles del_btn.Click
Dim delcmd As New OleDbCommand("delete from vijay where id=" & id_txt.Text & " ", conaccess)
delcmd.ExecuteNonQuery()
MsgBox("Record is deleted")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
Dim access As String = String.Format("INSERT INTO vijay (Name,Class,Branch,Gender,Age) VALUES('{0}','{1}','{2}','{3}','{4}')", name_txt.Text, class_txt.Text, branch_txt.Text, gen_txt.Text, age_txt.Text)
concmd.Connection = conaccess
concmd.CommandText = access
concmd.ExecuteNonQuery()
MsgBox("Record Successfully Saved")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub up_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles up_btn.Click
Dim access As String
access = "UPDATE vijay SET Name = '" & name_txt.Text & "', Age = '" & age_txt.Text & "', Gender ='" & gen_txt.Text & "' , Branch ='" & branch_txt.Text & "' , Class = '" & class_txt.Text & "' where id=" & id_txt.Text & ""
Dim cmd As New OleDbCommand(access, conaccess)
cmd.ExecuteNonQuery()
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
End Class
Use looping and parameter (to handle sql injection):
con.Open() 'Open connection to database
'Looping throung dgv
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
If IsDBNull(dgvEmpDetail.Rows(i).Cells("Emp_ID").Value) Then Exit For
Dim cmd As New SqlCommand("Update EmployeeDetail Set [Salary] = ?, [Experience]=?, [Skills]=? WHERE [Emp_ID] =?", con)
With cmd.Parameters
.AddWithValue("#Salary", dgvEmpDetail.Rows(i).Cells("Salary").Value )
.AddWithValue("#Experience", dgvEmpDetail.Rows(i).Cells("Experience").Value )
.AddWithValue("#Skills", dgvEmpDetail.Rows(i).Cells("Skills").Value )
.AddWithValue("#Emp_ID", dgvEmpDetail.Rows(i).Cells("Emp_ID").Value )
End With
cmd.ExecuteNonQuery()
Next i
con.Close() 'Close connection with Database

Calling and executing a stored procedure from sql into a vb.net textbox

I have created the following stored procedure in SQL Server:
CREATE Procedure CalcTotal
#InvoiceID Varchar(4)
As
Declare #Total int
Begin
SELECT
#Total = (TransportFee + EquipmentFee + LabourFee)
FROM
Invoice
WHERE
InvoiceID = #invoiceID
UPDATE Invoice
SET Total = #Total
WHERE InvoiceID = #invoiceID
END
My code for my form on Visual Basic are:
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Invoice
Dim sqlConn As New SqlConnection With {.ConnectionString = "Data Source=Hamsheed;Initial Catalog=assignment;Integrated Security=True"}
Dim sqlstr As String = "Select * From Invoice"
Dim MaxRows As Integer
Dim RowIndex As Integer = 0
Dim dt As New DataTable
Private Sub Invoice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim DataAdapter As New SqlDataAdapter(sqlstr, sqlConn)
DataAdapter.Fill(dt)
DataAdapter.Dispose()
MaxRows = dt.Rows.Count
InvoiceDetails()
cmbSearch.DataSource = dt
cmbSearch.DisplayMember = "FirstName"
End Sub
Sub InvoiceDetails()
txtInvoiceID.Text = CStr(dt.Rows(RowIndex)("InvoiceID"))
txtClientID.Text = CStr(dt.Rows(RowIndex)("ClientID"))
txtEmployeeID.Text = CStr(dt.Rows(RowIndex)("EmployeeID"))
txtFillInDate.Text = CStr(dt.Rows(RowIndex)("FillInDate"))
txtTransportFee.Text = CStr(dt.Rows(RowIndex)("TransportFee"))
txtEquipmentFee.Text = CStr(dt.Rows(RowIndex)("EquipmentFee"))
txtLabourFee.Text = CStr(dt.Rows(RowIndex)("LabourFee"))
txtTotal.Text = CStr(dt.Rows(RowIndex)("Total"))
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim InvoiceID As String = txtInvoiceID.Text
Dim ClientID As String = txtClientID.Text
Dim EmployeeID As String = (txtEmployeeID.Text)
Dim FillInDate As Date = CDate(txtFillInDate.Text)
Dim TransportFee As Integer = CInt(txtTransportFee.Text)
Dim EquipmentFee As Integer = CInt(txtEquipmentFee.Text)
Dim LabourFee As Integer = CInt(txtLabourFee.Text)
Dim Total As Integer = CInt(txtTotal.Text)
If CStr(dt.Rows(RowIndex)("paymentmethod")) = "Card" Then
radCard.Select()
ElseIf CStr(dt.Rows(RowIndex)("paymentmethod")) = "Cash" Then
radCash.Select()
Else
radCredit.Select()
End If
Dim sqlQuery As String = ("Exec Insert_Invoice #InvoiceID = ' " & InvoiceID & " ', #ClientID = '" & ClientID & "',#EmployeeID ='" & EmployeeID & "', #FillInDate ='" & FillInDate & "',#TransportFee='" & TransportFee & "',#EquipmentFee = '" & EquipmentFee & "',#LabourFee= '" & LabourFee & "',#Total= '" & Total)
Dim sqlcmnd As New SqlCommand(sqlQuery, sqlConn)
Try
sqlConn.Open()
Dim changes As Integer = sqlcmnd.ExecuteNonQuery()
sqlConn.Close()
MessageBox.Show(changes & "Changes Made")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Save()
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
dt.Rows(RowIndex)("InvoiceID") = CStr(txtInvoiceID.Text)
dt.Rows(RowIndex)("ClientID") = CStr(txtClientID.Text)
dt.Rows(RowIndex)("EmployeeID") = CStr(txtEmployeeID.Text)
dt.Rows(RowIndex)("FillInDate") = CStr(txtFillInDate.Text)
dt.Rows(RowIndex)("TransportFee") = CStr(txtTransportFee.Text)
dt.Rows(RowIndex)("EquipmentFee") = CStr(txtEquipmentFee.Text)
dt.Rows(RowIndex)("LabourFee") = CStr(txtLabourFee.Text)
dt.Rows(RowIndex)("Total") = CStr(txtTotal.Text)
Dim sqlquery As String = "exec edit_invoice '" & txtInvoiceID.Text & "', " & txtLabourFee.Text & ", " & txtTransportFee.Text & ", " & txtEquipmentFee.Text & ", '" & txtpaymentMethod.Text & "', '" & txtClientID.Text & "', '" & txtEmployeeID.Text & "', '" & txtFillInDate.Text & "', '" & txtTotal.Text & "'"
Dim sqlcmnd As New SqlCommand(sqlquery, sqlConn)
Try
sqlConn.Open()
Dim changes As Integer = sqlcmnd.ExecuteNonQuery()
sqlConn.Close()
MessageBox.Show(changes & "Changes Made")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Save()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtInvoiceID.Clear()
txtClientID.Clear()
txtEmployeeID.Clear()
txtFillInDate.Clear()
txtTransportFee.Clear()
txtEquipmentFee.Clear()
txtLabourFee.Clear()
txtTotal.Clear()
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If RowIndex <> MaxRows - 1 Then
RowIndex += 1
InvoiceDetails()
End If
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
RowIndex = MaxRows - 1
InvoiceDetails()
End Sub
Private Sub btnMainMenu_Click(sender As Object, e As EventArgs) Handles btnMainMenu.Click
SecretaryMainMenu.Show()
Me.Hide()
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim invoiceID As String = txtInvoiceID.Text
Dim SqlQuery As String = ("EXECUTE Delete_Invoice #InvoiceID = '" & InvoiceID & "'")
Dim cmd As New SqlCommand(SqlQuery, sqlConn)
Try
sqlConn.Open()
Dim changes As Integer = cmd.ExecuteNonQuery()
sqlConn.Close()
MessageBox.Show(changes & "Record Deleted")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Save()
dt.Rows(RowIndex).Delete()
End Sub
Sub Save()
Dim dataAdapter As New SqlDataAdapter(sqlstr, sqlConn)
Dim commandbuilder As New SqlCommandBuilder(dataAdapter)
dataAdapter.Update(dt)
dataAdapter.Dispose()
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
Dim searchitem As String = InputBox("Input Search invoice ID: ", "Search by ID")
Dim sresult As Boolean = False
searchitem = searchitem.Trim.ToUpper
For i As Integer = 0 To MaxRows - 1
If CStr(dt.Rows(i)("invoiceid")).ToUpper = searchitem Then
sresult = True
RowIndex = i
InvoiceDetails()
End If
Next
If sresult = False Then
MsgBox("No result found", MsgBoxStyle.OkOnly, "Information")
End If
End Sub
Private Sub txtinvoice_validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtInvoiceID.Validating
If Not txtInvoiceID.Text Like "I###" Then
e.Cancel = True
ErrorProvider1.SetError(txtInvoiceID, "Improper ID format")
End If
End Sub
Private Sub txtinvoice_validated(ByVal sender As Object, ByVal e As EventArgs) Handles txtInvoiceID.Validated
ErrorProvider1.SetError(txtInvoiceID, "")
End Sub
End Class
Now I want to call the stored procedure into the textbox Total, which will compute the 'transportFee, EquipmentFee and Labourfee' costs, and display the total into the textbox of txtTotal.Text
How do I write that piece of code?
use executescalar: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
remember to set the commandtype property of the command to stored procedure