VB.Net SQL issues - sql

I've been receiving errors with the following code below saying that the index is incorrect. I'm assuming this is an error with the SQL statement but I'm unsure what's wrong.
Private Sub btnStock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStock.Click
frmStock.Visible = True
Dim SQLCmd As String
SQLCmd = "SELECT PartID,PartName,PartStockLevel,MakeName,ModelName FROM tblParts WHERE PartStockLevel <= StockWarnLevel;"
RunSQLCmd("dt", SQLCmd)
Dim inc As Integer = 0
Dim NoLowStock As Boolean
If DataTable IsNot Nothing AndAlso DataTable.Rows.Count > 0 Then
frmStock.txtPartID.Text = DataTable.Rows(inc).Item(0)
frmStock.txtName.Text = DataTable.Rows(inc).Item(1)
frmStock.NUDStockLvl.Value = DataTable.Rows(inc).Item(2)
frmStock.txtMake.Text = DataTable.Rows(inc).Item(3)
frmStock.txtModel.Text = DataTable.Rows(inc).Item(4)
Else
frmStock.lblLowStock.Visible = True
frmStock.btnFirstRecord.Visible = False
frmStock.btnIncDown.Visible = False
frmStock.btnIncUp.Visible = False
frmStock.btnLastRecord.Visible = False
NoLowStock = True
End If
If NoLowStock = False Then
frmStock.Panel1.Visible = False
End If
End Sub
Public Sub RunSQLCmd(ByVal DTorDS As String, ByRef SQLCmd As String)
DataAdapter = New OleDb.OleDbDataAdapter(SQLCmd, con)
ConnectDB()
Try
If DTorDS = "dt" Then
DataTable = New DataTable
DataAdapter.Fill(DataTable)
Else
DataSet = New DataSet
DataAdapter.Fill(DataSet, "srcDataSet")
End If
Catch ex As Exception
con.Close()
End Try
con.Close()
End Sub
Thanks in advance!

The error probably comes from you looking at a row index that doesn't exist in the results. You should check that the table has rows before trying to get the data.
Something like this:
If DataTable IsNot Nothing AndAlso DataTable.Rows.Count >0 Then
... Code here...
End If

Try this simple way
dim dt as new datatable
using connection as new sqlconnection("server=SERVER;database=DATABASE;uid=USERID;pwd=PASSWORD")
connection.open()
using cmd as new sqlcommand("SELECT PartID,PartName,PartStockLevel,MakeName,ModelName FROM tblParts WHERE PartStockLevel <= StockWarnLevel", connection)
dt.load(cmd.executereader)
end using
end using

Related

getting data from mysql database by using thread in vb.,net

I'm trying to get data from database but I got an error:
There is already an open DataReader associated with this Connection
which must be closed first
what I did is the following codes:
1: I have a module that contains the following sub:
Public Function CheckServerConn() As Boolean
Try
_ServerConnStr = New MySqlConnection(My.Settings.DbPath)
If _ServerConnStr.State = ConnectionState.Open Then
_ServerConnStr.Close()
End If
If _ServerConnStr.State = ConnectionState.Closed Then
_ServerConnStr.Open()
Return True
End If
Catch ex As Exception
MsgBox("Check The Conn " & ex.Message, Me_MsgInfoStyle, Me_MsgCaptionStr)
Return False
End Try
#Disable Warning BC42353 ' Function doesn't return a value on all code paths
End Function
2: I have this subroutine in class called "ClsMySql":
'GetData
Public Sub GetData(ByVal SqlStr As String, ByVal xDt As DataTable, ByVal xPar() As MySqlParameter)
Using xCmd As New MySqlCommand() With {
.CommandType = CommandType.Text,
.CommandText = SqlStr,
.Connection = _ServerConnStr,
.CommandTimeout = 5000000
}
If xPar IsNot Nothing Then
For i As Integer = 0 To xPar.Length - 1
xCmd.Parameters.Add(xPar(i))
Next
End If
Using xDa As New MySqlDataAdapter(xCmd)
xDa.Fill(xDt)
End Using
xDt.Dispose()
End Using
End Sub
3: I have a class for the table that have the following method:
Public Sub MySql_Get_Daf()
xClsMySql = New ClsMySql
Dim SqlStr As String = "SELECT RegID,RegType, tblregs1.`RegRef`,`RegDate`, COUNT(`RegdID`) AS xCount
,IF(COUNT(`RegdID`) =3,'Ok','Error') AS xResult FROM tblregs1
INNER JOIN tblregs2 ON tblregs2.RegRef = tblregs1.RegRef
WHERE `RegType` = 'Daf'
GROUP BY tblregs1.`RegRef`
ORDER BY COUNT(`RegdID`) ASC"
Dt_Get_Daf = New DataTable()
xClsMySql.GetData(SqlStr, Dt_Get_Daf, Nothing)
End Sub
Public Sub MySql_Get_Qbd()
xClsMySql = New ClsMySql
Dim SqlStr As String = "SELECT RegID,RegType, tblregs1.`RegRef`,`RegDate`, COUNT(`RegdID`) AS xCount
,IF(COUNT(`RegdID`) =3,'Ok','Error') AS xResult FROM tblregs1
INNER JOIN tblregs2 ON tblregs2.RegRef = tblregs1.RegRef
WHERE `RegType` = 'Qbd'
GROUP BY tblregs1.`RegRef`
ORDER BY COUNT(`RegdID`) ASC"
Dt_Get_Qbd = New DataTable()
xClsMySql.GetData(SqlStr, Dt_Get_Qbd, Nothing)
End Sub
Public Sub MySql_Get_All()
Dim xThread As Thread = New Thread(Sub() MySql_Get_Daf())
Dim xThread2 As Thread = New Thread(Sub() MySql_Get_Qbd())
xThread.Start()
xThread2.Start()
End Sub
when I call MySql_Get_All by a button it gives me the next error:
There is already an open DataReader associated with this Connection
which must be closed first
can anybody tell me what's the wrong here

Delete Row / Remove Row

I want to delete my rows in gridview, but when I try many code the error are same.
When I try this
Using sqlCon As New SqlConnection(PyrDLL.Koneksi.ConnectionString)
Using cmd As New SqlCommand()
cmd.CommandText = "xyz"
cmd.Connection = sqlCon
sqlCon.Open()
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
Gridview1.DataSource = dt
Gridview1.DataBind()
sqlCon.Close()
If Gridview1.Rows.Count = 0 Then
Dim dtempty As DataTable = Nothing
dtempty = (DirectCast(Gridview1.DataSource, DataTable)).Clone()
dtempty.Rows.Add(dtempty.NewRow())
Gridview1.DataSource = dtempty
Gridview1.DataBind()
Gridview1.Rows(0).Visible = False
'Gridview1.Rows(0).Controls.Clear()
Else
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("rupiah") = PyrDLL.Decrypt(dt.Rows(i)("rupiah"))
dt.Rows(i)("rupiah") = Decimal.Parse(dt.Rows(i)("rupiah")).ToString()
'i = i + 1
Next
Gridview1.DataBind()
For i As Integer = Gridview1.Rows.Count - 1 To 1 Step -1
Dim row As GridViewRow = Gridview1.Rows(i)
Dim prevrow As GridViewRow = Gridview1.Rows(i - 1)
If (TryCast(Gridview1.Rows(i).Cells(1).FindControl("lblketerangan"), Label).Text.ToString() = TryCast(Gridview1.Rows(i - 1).Cells(1).FindControl("lblketerangan"), Label).Text.ToString()) And (TryCast(Gridview1.Rows(i).Cells(0).FindControl("lblcomp"), Label).Text.ToString() = TryCast(Gridview1.Rows(i - 1).Cells(0).FindControl("lblcomp"), Label).Text.ToString()) Then
Dim total As Integer = Convert.ToDecimal(TryCast(Gridview1.Rows(i - 1).Cells(2).FindControl("lblrupiah"), Label).Text)
Dim total2 As Integer = Convert.ToDecimal(TryCast(Gridview1.Rows(i).Cells(2).FindControl("lblrupiah"), Label).Text)
Dim total3 As Decimal
total3 = total + total2
DirectCast(Gridview1.Rows(i - 1).Cells(2).FindControl("lblrupiah"), Label).Text = Decimal.Parse(total3).ToString()
row.Visible = False
'Gridview1.Rows.Remove(Gridview1.Rows(i)) <--- if i comment here its run without problem
End If
Next
End If
End Using
End Using
the error
Remove' is not a member of 'System.Web.UI.WebControls.GridViewRowCollection'
Can you help me?
now, i hide the row after i sum it but i want to auto delete / remove row after i sum it not only hide
Thanks
I am not sure what you are trying to do when there are no rows, the gridview would be empty
You should do the following instead:
'Call GetData() every time you want to bind data to the gridview
Private Function GetData()
Gridview1.DataSource = Nothing
Gridview1.DataBind()
Dim strQuery = "SELECT..."
Dim dt As New DataTable()
Using sqlCon As New SqlConnection(PyrDLL.Koneksi.ConnectionString)
Using cmd As New SqlCommand(strQuery, sqlCon)
'Add cmd parameters as required to prevent SqlInjection
sqlCon.Open()
Using ada As New SqlDataAdapter(cmd)
ada.Fill(dt)
Gridview1.DataSource = dt
Gridview1.DataBind()
End Using
End Using
End Using
End Function
When handling the data in the gridview you can use RowDataBound, you could then call a separate function to handle deleting a row after your logic is handled where the criteria is met to delete a row
Protected Sub Gridview1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles Gridview1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'Handle databound logic
End If
End Sub
You should be able to tailor this to your needs, just called GetData() everytime you need to rebind data to the gridview
I solved my problem
i cant remove rows from data gridview but i remove data from data table and bind it after thats
thanks everyone

How to convert total time to minutes

This was the error msg im gettingenter image description hereI have a database that has a row "Total_Time" (time).
It is in the format HH:MM:SS. I need the code to convert the "Total_time" to minutes.
For example, if Total_time = 01:30:00, the answer should be Total_minutes = 90,
and I want to multiply the total_minutes with "Other" (int variable).
Below is what I have tried:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
con = New System.Data.SqlClient.SqlConnection
Try
con.ConnectionString = "Data Source=Vicky-pc\sqlexpress;Initial Catalog=customer_details;Integrated Security=True;Pooling=False"
con.Open()
Dim cm As SqlClient.SqlCommand
cm = New SqlClient.SqlCommand("SELECT * FROM customer_details WHERE Id=#id", con)
cm.Parameters.AddWithValue("#id", TextBox5.Text)
dr = cm.ExecuteReader()
While dr.Read()
Dim tt As Double
tt = dr("Total_Time").ToString
Dim other As Double
other = dr("Other").ToString
Dim str() As String
Dim strmin As Double
str = Split(tt.ToString, ":")
strmin = (CDbl(str(1)) * 60 + CDbl(str(2)) + CDbl(str(3)) / 60).ToString
Dim total As Decimal
total = strmin + other
Label7.Text = total.ToString
End While
Catch ex As Exception
End Try
End Sub
but when i click nothing is happening label7 is not displaying any values
Thanks in advance.
Dim Total_minutes As Double = CDate("1:23:45").TimeOfDay.TotalMinutes ' 83.75
To avoid similar errors, I would highly recommend using Option Strict
Dim Total_Time As DateTime = Convert.ToDateTime(dr!Total_Time)
Dim Total_minutes# = Total_Time.TimeOfDay.TotalMinutes
Dim Other# = Val(dr!Other)
Dim total# = Total_minutes * Other
Label7.Text = total.ToString
Try below
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
con = New System.Data.SqlClient.SqlConnection
Try
con.ConnectionString = "Data Source=Vicky-pc\sqlexpress;Initial Catalog=customer_details;Integrated Security=True;Pooling=False"
con.Open()
Dim cm As SqlClient.SqlCommand
cm = New SqlClient.SqlCommand("SELECT * FROM customer_details WHERE Id=#id", con)
cm.Parameters.AddWithValue("#id", TextBox5.Text)
dr = cm.ExecuteReader()
While dr.Read()
Dim other As TimeSpan
Dim tt As TimeSpan
If TimeSpan.TryParse(dr("Total_Time"), tt) Then
If TimeSpan.TryParse(dr("Other"), other) Then
tt = tt.Add(other)
Else
'Do something like show error message for incorrect data for dr("Other")
End If
Label7.Text = tt.TotalMinutes.ToString
Else
'Do something like show error message for incorrect data for dr("Total_Time")
End If
End While
Catch ex As Exception
End Try
End Sub
If time is more than 24:00:00, use below code
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
con = New System.Data.SqlClient.SqlConnection
Try
con.ConnectionString = "Data Source=Vicky-pc\sqlexpress;Initial Catalog=customer_details;Integrated Security=True;Pooling=False"
con.Open()
Dim cm As SqlClient.SqlCommand
cm = New SqlClient.SqlCommand("SELECT * FROM customer_details WHERE Id=#id", con)
cm.Parameters.AddWithValue("#id", TextBox5.Text)
dr = cm.ExecuteReader()
While dr.Read()
Try
Dim dataTime As String = dr("Total_Time").ToString
dataTime = dataTime.Split("."c)(0).ToString
Dim tt As New TimeSpan(Integer.Parse(dataTime.Split(":"c)(0)), Integer.Parse(dataTime.Split(":"c)(1)), Integer.Parse(dataTime.Split(":"c)(2)))
dataTime = dr("Other").ToString
dataTime = dataTime.Split("."c)(0).ToString
Dim other As New TimeSpan(Integer.Parse(dataTime.Split(":"c)(0)), Integer.Parse(dataTime.Split(":"c)(1)), Integer.Parse(dataTime.Split(":"c)(2)))
tt = tt.Add(other)
dataTime = tt.TotalMinutes.ToString
Catch ex As Exception
'do something here as string is not a time
End Try
End While
Catch ex As Exception
End Try
End Sub
Don't keep switching to strings... and use a Timespan
If your label never changes then the routine must be erroring out, examine the error from the catch statement. However from your image it looks like Other has no value.
And you should ALWAYS test for dbnull when using databases. DBNull has some weird behaviours in Math and Boolean comparisons.
Replace your while loop with this
If Not Dr.read OrElse IsDBNull(Dr("Total_time")) OrElse IsDBNull(Dr("Other")) Then
Label7.text = "ERR"
Else
Dim ts As TimeSpan = TimeSpan.Parse(dr("Total_time").ToString)
Label7.text = (ts.TotalMinutes * Dr("Other")).ToString
End If
PS: Your question says multiply by Other but your form/code says Add... I went with the question.

DataGridView not Refreshing

I have a SQL table that looks similar to this:
1 | a | stuff...
2 | a | stuff...
3 | b | stuff...
4 | a | stuff...
5 | b | stuff...
I only want to show:
3 | b | stuff...
5 | b | stuff...
So I use this code to load the DataGridView:
Private Sub GetData()
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
' Create an instance of a DataAdapter.
Dim daInstTbl As _
New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", objConn)
' Create an instance of a DataSet, and retrieve data from the Authors table.
daInstTbl.FillSchema(dsNewInst, SchemaType.Source)
daInstTbl.Fill(dsNewInst)
' Create a new instance of a DataTable
MyDataTable = dsNewInst.Tables(0)
daInstTbl.Update(dsNewInst)
End Sub
Private Sub InitializeDataGridView()
Try
' Set up the DataGridView.
With Me.DataGridView1
' Set up the data source.
.DataSource = MyDataTable
End With
Catch ex As SqlException
MessageBox.Show(ex.ToString, _
"ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
System.Threading.Thread.CurrentThread.Abort()
End Try
End Sub
Everything works great and until I want to delete 3 and renumber 4 and 5 down one to become 3 and 4. I have loops handling everything and the database is receiving the correct data except my DataGridView only shows the updates when I restart the program.
Here's my delete code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim daInstDeleteTbl As New SqlDataAdapter("SELECT * FROM Table", objConn)
Dim dsDeleteInst As New DataSet
Dim MyDeleteTable As DataTable
' Create an instance of a DataSet, and retrieve data from the Authors table.
daInstDeleteTbl.FillSchema(dsDeleteInst, SchemaType.Source)
daInstDeleteTbl.Fill(dsDeleteInst)
' Create a new instance of a DataTable
MyDeleteTable = dsDeleteInst.Tables(0)
'Begin Delete Code
Dim DeleteID, DeleteIndex As Integer
Dim MadeChange As Boolean = False
Integer.TryParse(TextBox1.Text, DeleteID)
Dim dgvIndexCount As Integer = MyDeleteTable.Rows.Count - 1
If MyDeleteTable.Rows(dgvIndexCount).Item(0) > DeleteID Then
Dim counter As Integer = -1
For Each row As DataRow In MyDeleteTable.Rows
counter += 1
If row.Item("Column") = DeleteID Then
DeleteIndex = counter
End If
Next
MadeChange = True
End If
drCurrent = MyDeleteTable.Rows.Find(DeleteID)
drCurrent.Delete()
If MadeChange = True Then
Dim i As Integer = 0
For i = DeleteIndex + 1 To dgvIndexCount
MyDeleteTable.Rows(i).Item(0) = MyDeleteTable.Rows(i).Item(0) - 1
Next
End If
'Send Changes to SQL Server
Dim objCommandBuilder As New SqlCommandBuilder(daInstDeleteTbl)
daInstDeleteTbl.Update(dsDeleteInst)
Dim daInstTbl As _
New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", objConn)
Dim objCommandReBuilder As New SqlCommandBuilder(daInstTbl)
daInstTbl.Update(dsNewInst)
End Sub
I think I am doing a lot of extra work just to do this wrong. Any ideas? Thanks.
When you invoke SqlDataAdapter.Update() the adapter updates the values in the database by executing the respective INSERT, UPDATE, or DELETE (from MSDN). The SELECT command is not executed. So you need to do it like this:
Insert/Update/Delete:
daInstTbl.Update(dsNewInst)
Select:
daInstTbl.Fill(dsNewInst)
Commit:
dsNewInst.AcceptChanges()
Example
Private connection As SqlConnection
Private adapter As SqlDataAdapter
Private data As DataSet
Private builder As SqlCommandBuilder
Private grid As DataGridView
Private Sub InitData()
Me.SqlSelect(firstLoad:=True, fillLoadOption:=LoadOption.OverwriteChanges, acceptChanges:=True)
Me.grid.DataSource = Me.data
Me.grid.DataMember = "Table"
End Sub
Public Sub SaveData()
Me.SqlInsertUpdateAndDelete()
Me.SqlSelect(fillLoadOption:=LoadOption.OverwriteChanges, acceptChanges:=True)
End Sub
Public Sub RefreshData(preserveChanges As Boolean)
Me.SqlSelect(fillLoadOption:=If(preserveChanges, LoadOption.PreserveChanges, LoadOption.OverwriteChanges))
End Sub
Private Sub SqlSelect(Optional firstLoad As Boolean = False, Optional ByVal fillLoadOption As LoadOption = LoadOption.PreserveChanges, Optional acceptChanges As Boolean = False)
If (firstLoad) Then
Me.data = New DataSet()
Me.connection = New SqlConnection("con_str")
Me.adapter = New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", connection)
Me.builder = New SqlCommandBuilder(Me.adapter)
End If
Me.connection.Open()
If (firstLoad) Then
Me.adapter.FillSchema(Me.data, SchemaType.Source, "Table")
End If
Me.adapter.FillLoadOption = fillLoadOption
Me.adapter.Fill(Me.data, "Table")
If (acceptChanges) Then
Me.data.Tables("Table").AcceptChanges()
End If
Me.connection.Close()
End Sub
Private Sub SqlInsertUpdateAndDelete()
If (Me.connection.State <> ConnectionState.Open) Then
Me.connection.Open()
End If
Me.adapter.Update(Me.data, "Table")
Me.connection.Close()
End Sub
PS: (Untested code)
My solution was to change the way I was declaring variables. Before I had:
Dim daInstTbl As _
New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", objConn)
The affect was that recalling the subroutine ignored this line because the variable daInstTbl was already declared previously. The solution was:
' Delete old instance of a Data____ classes
da = Nothing
ds = Nothing
dt = Nothing
If GetAll = False Then
da = New SqlDataAdapter(sSelCmd, objConn)
Else
da = New SqlDataAdapter(sSelAllCmd, objConn)
End If
' Create an instance of a DataSet, and retrieve data from the Authors table.
ds = New DataSet
da.FillSchema(ds, SchemaType.Source)
da.Fill(ds)
This cleared the information and allowed me to assign a new value. My subroutines serve double duty by assigning two query strings and then using an optional boolean to determine which version to use.
Dim sSelCmd As String = "SELECT * FROM Table WHERE Coloumn= 'b'"
Dim sSelAllCmd As String = "SELECT * FROM Table"
Private Sub GetData(Optional ByVal GetAll As Boolean = False)
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
And that leads into the code above! Thanks for the help. Some of your concepts got my thoughts turning in the right direction and motivated me to clean up my code into a much more readable form.

VB.NET DataSet Update

Why my set of codes didn't update in DataSet? Then it goes to Error. Please anyone check this code and point me out where I am missing. Thanks in advance!
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=username;Password=pwds")
Dim dadPurchaseInfo As New SqlDataAdapter
Dim dsPurchaseInfo As New DataSet1
Try
Dim dRow As DataRow
conxMain.Open()
Dim cmdSelectCommand As SqlCommand = New SqlCommand("SELECT * FROM Stock", conxMain)
cmdSelectCommand.CommandTimeout = 30
dadPurchaseInfo.SelectCommand = cmdSelectCommand
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo)
dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")
For Each dRow In dsPurchaseInfo.Tables("Stock").Rows
If CInt(dRow.Item("StockID").ToString()) = 2 Then
dRow.Item("StockCode") = "Re-Fashion[G]"
End If
Next
dadPurchaseInfo.Update(dsPurchaseInfo, "Stock")
Catch ex As Exception
MsgBox("Error : ")
Finally
If dadPurchaseInfo IsNot Nothing Then
dadPurchaseInfo.Dispose()
End If
If dsPurchaseInfo IsNot Nothing Then
dsPurchaseInfo.Dispose()
End If
If conxMain IsNot Nothing Then
conxMain.Close()
conxMain.Dispose()
End If
End Try
End Sub
Does your condition in the loop get executed (set a break point!)? Where is the error thrown? What error?
Also, why does it use ToString at all? This seems redundant.
If CInt(dRow.Item("StockID")) = 2 Then
Should be enough.
Finally, you’re performing redundant cleanup:
If conxMain IsNot Nothing Then
conxMain.Close()
conxMain.Dispose()
End If
Dispose implies Close – no need to perform both operations:
Close and Dispose are functionally equivalent.
[Source: MSDN]
Does your dataAdapter has update command ?
(it looks like it doesn't - so it doesn't know what do to with update....)
Here is an Update Command example:(for an employee table with 3 columns - as listed below:
UPDATE [Employee]
SET [name] = #name
, [manager] = #manager
WHERE (([id] = #Original_id) AND
((#IsNull_name = 1 AND [name] IS NULL) OR
([name] = #Original_name)) AND
((#IsNull_manager = 1 AND [manager] IS NULL) OR
([manager] = #Original_manager)));
SELECT id
, name
, manager
FROM Employee
WHERE (id = #id)
You can see it is a general update that can handle changes in any field.
I got it from the error correction of my program by Konard Rudolph!
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=username;Password=pwds")
Dim dadPurchaseInfo As New SqlDataAdapter
Dim dsPurchaseInfo As New DataSet1
Try
Dim dRow As DataRow
conxMain.Open()
dadPurchaseInfo.SelectCommand = New SqlCommand("SELECT * FROM Stock", conxMain)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo)
dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")
For Each dRow In dsPurchaseInfo.Tables("Stock").Rows
If CInt(dRow.Item("StockID")) = 2 Then
dRow.Item("StockCode") = "Re-Fashion(H)"
End If
Next
dadPurchaseInfo.Update(dsPurchaseInfo, "Stock")
Catch ex As Exception
MsgBox("Error : " & vbCrLf & ex.Message)
Finally
If dadPurchaseInfo IsNot Nothing Then
dadPurchaseInfo.Dispose()
End If
If dsPurchaseInfo IsNot Nothing Then
dsPurchaseInfo.Dispose()
End If
If conxMain IsNot Nothing Then
conxMain.Dispose()
End If
End Try
End Sub
The above set of code work to update with DataSet! Thanks to stackoverflow community and who answered my question.
Here is ref:
How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual Basic .NET
How to update a database from a DataSet object by using Visual Basic .NET
p.s: Like o.k.w said : The Table must have primary key. Thanks o.k.w!
--MENU--
Dim login As New LoginClass
login.ShowDialog()
--CONEXION--
Private conec As SqlConnection
Dim stringCon As String = "Data Source= ;Initial Catalog=;Persist Security Info=True;User ID=;Password="
Public ReadOnly Property prConec() As Object
Get
Return conec
End Get
End Property
Public Sub Conectar()
Try
conec = New SqlConnection(stringCon)
If conec.State <> ConnectionState.Open Then
conec.Open()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
--BUSCAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_cliente", funciones.prConec)
Dim dt As New DataTable
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("#i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "B"
dt.Load(coman.ExecuteReader())
grdClientes.DataSource = dt
--INSERTAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_articulo", funciones.prConec)
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("#i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "I"
coman.ExecuteNonQuery()
Buscar()
Limpiar()
--COMBO--
Dim dt As New DataTable
dt.Columns.Add("Codigo")
dt.Columns.Add("Descripcion")
Dim dr1 As DataRow = dt.NewRow
dr1.Item("Codigo") = "A"
dr1.Item("Descripcion") = "Activo"
dt.Rows.Add(dr1)
Dim dr2 As DataRow = dt.NewRow
dr2.Item("Codigo") = "I"
dr2.Item("Descripcion") = "Inactivo"
dt.Rows.Add(dr2)
cmbEstado.DataSource = dt
cmbEstado.ValueMember = "Codigo"
cmbEstado.DisplayMember = "Descripcion"
--GRIDVIEW--
--1--
Dim grdFila As DataGridViewRow = grdClientes.CurrentRow
txtCedula.Text = grdFila.Cells(0).Value
--2--
If DataGridProductos.CurrentCell.ColumnIndex = 0 Then
Dim FLstArticulos As New FLstArticulos
FLstArticulos.ShowDialog()
DataGridProductos.CurrentRow.Cells(0).Value = FLstArticulos.PrIdArticulo
End If
--GRIDVIEW.CELLENDEDIT--
If DataGridProductos.CurrentCell.ColumnIndex = 3 Then
Dim precio As New Double
Dim cantidad As New Double
precio = CDbl(grdRow.Cells(2).Value)
cantidad = CDbl(grdRow.Cells(3).Value)
DataGridProductos.CurrentRow.Cells(4).Value = PLTotalFilaItem(cantidad, precio)
PLCargaTotales()
End If
Sub PLCargaTotales()
Dim subTotal As Double
Dim iva As Double
For Each grd As DataGridViewRow In DataGridProductos.Rows
If Not String.IsNullOrEmpty(grd.Cells(4).Value) Then
subTotal = subTotal + CDbl(grd.Cells(4).Value)
End If
Next grd
txtSubtotal.Text = subTotal.ToString
iva = Decimal.Round(subTotal`enter code here` * 0.12)
txtIva.Text = iva.ToString
txtTotalPagar.Text = (subTotal + iva).ToString
End Sub