VB.NET DataSet Update - vb.net

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

Related

Database record not updated

Hi everyone I'm new to here, I have problem to update my database record in VB ASP.NET webform. My code below will return dialog box that says record updated successfully when cmd.ExecuteNonQuery() > 0 but the record in database not being updated in fact. Sorry for my bad english. Please help thanks in advance.
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim staffUsername As String = Session("StaffUsername").ToString()
Dim staffFNm As String = txtStaffFNm.Text
Dim staffLNm As String = txtStaffLNm.Text
Dim staffEmail As String = txtStaffCpnyEmail1.Text + txtStaffCpnyEmail2.Text
Dim staffBDay As String = txtBirthday.Text
Dim staffPhone As String = txtPhoneNo.Text
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("SupportSystemDB").ConnectionString)
con.Open()
Dim myCommand As New SqlCommand("UPDATE STAFF SET StaffFNm = #staffFNm, StaffLNm = #staffLNm, StaffEmail = #staffEmail, StaffBirthday = #staffBDay, StaffPhone = #staffPhone WHERE StaffUsernm = #staffUsernm", con)
myCommand.Parameters.AddWithValue("#staffFNm", staffFNm)
myCommand.Parameters.AddWithValue("#staffLNm", staffLNm)
myCommand.Parameters.AddWithValue("#staffEmail", staffEmail)
myCommand.Parameters.AddWithValue("#staffBDay", staffBDay)
myCommand.Parameters.AddWithValue("#staffPhone", staffPhone)
myCommand.Parameters.AddWithValue("#staffUsernm", staffUsername)
If myCommand.ExecuteNonQuery() > 0 Then
Response.Write("<script>alert('Your Account Info Has Been Successfully Updated.');</script>")
con.Close()
Else
Response.Write("<script>alert('Record Update Failed.');</script>")
End If
End Using
End Sub

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.

Procedure or function 'p_xxx ' has too many arguments specified

I get the error at this line: sqlDataAdapDelProtocol.Fill(dsDelProtocol, "dsProtocols"), I dint understand why. The error states : Procedure or function p_GetLinkedProcuduresProtocol has too many arguments specified
Protected Sub btnDeletePTC_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim sqlString As String = String.Empty
Dim PTC_ID As Integer
sqlString = "p_GetLinkedProcuduresProtocol"
Dim sqlConnDelProtocol As New SqlClient.SqlConnection(typicalConnectionString("MyConn").ConnectionString)
sqlConnDelProtocol.Open()
Dim sqlDataAdapDelProtocol As New SqlClient.SqlDataAdapter(sqlString, sqlConnDelProtocol)
sqlDataAdapDelProtocol.SelectCommand.CommandType = CommandType.StoredProcedure
Dim sqlParProtocolName As New SqlClient.SqlParameter("#PTC_ID", SqlDbType.Int, 255)
sqlDataAdapDelProtocol.SelectCommand.Parameters.Add(sqlParProtocolName)
Dim dsDelProtocol As New DataSet
Dim MessageAud = "Are you sure you want to delete this question, the question is linked to:"
Dim MessageNoAud = "Are you sure you want to delete this question"
sqlDataAdapDelProtocol.SelectCommand.Parameters.AddWithValue("PTC_ID", PTC_ID)
sqlDataAdapDelProtocol.Fill(dsDelProtocol, "dsProtocols")
If dsDelProtocol.Tables("dsProtocols").Rows.Count > 0 Then
lblMessageSure.Text = (CType(MessageAud, String))
For Each dr As DataRow In dsDelProtocol.Tables(0).Rows
lblAudits = (dr("dsProtocols"))
Next
Else
lblMessageSure.Text = (CType(MessageNoAud, String))
End If
Dim success As Boolean = False
Dim btnDelete As Button = TryCast(sender, Button)
Dim row As GridViewRow = DirectCast(btnDelete.NamingContainer, GridViewRow)
Dim cmdDelete As New SqlCommand("p_deleteProtocolStructure")
cmdDelete.CommandType = CommandType.StoredProcedure
cmdDelete.Parameters.AddWithValue("PTC_ID", PTC_ID)
Call DeleteProtocol(PTC_ID)
conn = NewSqlConnection(connString, EMP_ID)
cmdDelete.Connection = conn
If Not conn Is Nothing Then
If conn.State = ConnectionState.Open Then
Try
success = cmdDelete.ExecuteNonQuery()
Call UpdateProtocolNumbering(PTS_ID)
txtAddPTCNumber.Text = GetNextNumber(PTS_ID)
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "TreeView", _
"<script language='javascript'>" & _
" parent.TreeView.location='TreeView.aspx?MainScreenURL=Protocols.aspx&PTS_ID=" & PTS_ID & "';" & _
"</script>")
conn.Close()
Catch ex As Exception
success = False
conn.Close()
Throw ex
End Try
End If
End If
If success = True Then
Call GenerateQuestionsGrid()
Call Message(Me, "pnlMessage", "Question successfully deleted.", Drawing.Color.Green)
Else
Call Message(Me, "pnlMessage", "Failed to delete Question.", Drawing.Color.Red)
End If
End Sub
You are adding the same parameter twice, once without a value, then with a value. Instead of adding it another time, set the value on the parameter that you already have.
Replace this:
sqlDataAdapDelProtocol.SelectCommand.Parameters.AddWithValue("PTC_ID", PTC_ID)
with this:
sqlParProtocolName.Vaue = PTC_ID
Side note: Always start parameter names for Sql Server with #. The parameter constructor will add it if it's not there so it will work without it, but this is an undocumented feature, so that could change in future versions.

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 SQL issues

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