Deleting record from a datatable - vb.net

I have the following code that works fine on the first execution but doesn't seem to find the previously deleted record when executed again. Any advice.Thanks
Private Sub TvContainer_NodeSelected(sender As Object, e As ComponentArt.Web.UI.TreeViewNodeEventArgs) Handles TvContainer.NodeSelected
Dim no As Integer
Dim dtpackunit As New DataTable
dtShipItem = Session("dsShipItem")
dtpackunit = Session("dsUnit")
no = TvContainer.SelectedNode.ID
Dim dt As DataTable = dtpackunit
Dim rows = dt.[Select]("No <> " & no)
For Each row In rows
row.Delete()
Next
gridbox.DataSource = dtpackunit
gridbox.DataBind()
gridship.DataSource = dtShipItem '.Select(filterExp, Nothing, Nothing)
gridship.DataBind()
End Sub

Related

Moving rows up and down in a datagridview and updating the database

I have a datagridview and I am getting all the data from a sql database I want to be able to move rows from one position to the other either up or down and it should also reflect the same in the database.
Currently this is what I have done and it does move the items as desired ( am adding 100 to the value of the column that am using to move up and subtracting 100 when moving down) but the problem with this is that if it find that the value of the next item in the row is lower, it doesnt move or if you add 100 then its value suddenly becomes more that 3 items above it, it doesnt move to the next position instead it moves 3 positions up, how can I simplify it to make it move just 1 row above or below respectively.
Private Sub BntMoveUp_Click(sender As Object, e As EventArgs) Handles BntMoveUp.Click
For i As Integer = 0 To DataGridView2.Rows.Count() - 1
Dim c As Boolean
c = DataGridView2.Rows(i).Cells(0).Value
' if the checkbox cell is checked
If c = True Then
' MessageBox.Show("Checked")
Dim cid As Integer = DataGridView2.Rows(i).Cells(1).Value
Dim cid2 As Integer = DataGridView2.Rows(i - 1).Cells(1).Value
Str = "update Production..CMBGSeat_Staging set [Priority] =[Priority] > 1 where cid=" & cid
updaterecords(Str)
Dim cmd As Odbc.OdbcCommand
Dim LDataadapter As Odbc.OdbcDataAdapter
Dim MyDataset As DataSet
Dim insert As String
con()
insert = "select * from Production..CMBGSeat_Staging where DateCompleted is null order by Priority desc"
cmd = New Odbc.OdbcCommand(insert, sqlcon)
LDataadapter = New Odbc.OdbcDataAdapter
LDataadapter.SelectCommand = cmd
MyDataset = New DataSet
' MyDataset = New DataSet
LDataadapter.Fill(MyDataset)
DataGridView2.DataSource = MyDataset.Tables(0)
' if not
Else
' MessageBox.Show("Not Checked")
End If
Next
End Sub
Private Sub BtnMoveDown_Click(sender As Object, e As EventArgs) Handles BtnMoveDown.Click
For i As Integer = 0 To DataGridView2.Rows.Count() - 1
Dim c As Boolean
c = DataGridView2.Rows(i).Cells(0).Value
'If the Then checkbox cell Is checked
If c = True Then
' MessageBox.Show("Checked")
Dim cid As Integer = DataGridView2.Rows(i).Cells(1).Value
Dim cid2 As Integer = DataGridView2.Rows(i + 1).Cells(1).Value
Str = "update Production..CMBGSeat_Staging set [Priority] =[Priority] < 1 where cid=" & cid
updaterecords(Str)
Dim cmd As Odbc.OdbcCommand
Dim LDataadapter As Odbc.OdbcDataAdapter
Dim MyDataset As DataSet
Dim insert As String
con()
insert = "select * from Production..CMBGSeat_Staging where DateCompleted is null order by Priority desc"
cmd = New Odbc.OdbcCommand(insert, sqlcon)
LDataadapter = New Odbc.OdbcDataAdapter
LDataadapter.SelectCommand = cmd
MyDataset = New DataSet
MyDataset = New DataSet
LDataadapter.Fill(MyDataset)
DataGridView2.DataSource = MyDataset.Tables(0)
' if not
Else
'MessageBox.Show("Not Checked")
End If
Next
End Sub

UltraWinGrid deletes top record rather than the selected one

I've got an ultrawingrid that I can select rows on, and need to be able to delete the highlighted row. At the moment, it calls the database SQL query that I wrote but instead of deleting the record in the row I selected, it deletes the record in the top row instead. Can anybody work out why?
Private Sub btnDeleteIncident_Click(sender As Object, e As EventArgs) Handles btnDeleteIncident.Click
Try
Dim rowValue = ugHistory.Selected.Rows
Dim rowToDelete = ugHistory.Rows(0).Cells(0).Value.ToString
Dim removeIncident As MsgBoxResult
removeIncident = MsgBox("Are you sure you wish to delete this incident?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm")
If removeIncident = MsgBoxResult.Yes Then
Database.deleteIncident(rowToDelete)
txtClientSave.Text = ""
rtbProblem.Text = ""
rtbSolution.Text = ""
dtpStart.Value = Date.Today
dtpEnd.Value = Date.Today
dtpStartTime.Value = DateTime.Now
dtpEndTime.Value = DateTime.Now
cboxSolved.Checked = False
btnUpdate.Hide()
btnSave.Show()
ElseIf removeIncident = MsgBoxResult.No Then
loadIncidents()
End If
Catch Ex As Exception
MsgBox("No incidents to delete")
End Try
loadIncidents()
End Sub
Database SQL query;
Public Shared Sub deleteIncident(ByVal supportID As Integer)
Connect()
Dim Dc As New OleDbCommand
Dc.Connection = Con
Dc.CommandText = "DELETE * FROM tblIncidents WHERE([supportID] = " & supportID & ")"
Dc.ExecuteNonQuery()
Disconnect()
End Sub
You are taking the value for rowToDelete from the first row of the grid not from the current active row
I suggest you to change this line
Dim rowToDelete = ugHistory.Rows(0).Cells(0).Value.ToString
to
Dim rowToDelete = ugHistory.ActiveRow.Cells(0).Value.ToString
Also, it is always better to follow a safe approach when handling reference objects like 'ActiveRow', so before running your code add a test for a valid
ActiveRow
if ugHistory.ActiveRow Is Nothing Then
Return
End If
Dim rowToDelete = ugHistory.ActiveRow.Cells(0).Value.ToString

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.

Update old data and add new data using tableadapter in vb.net

My code should update old records and at the same time if the a new record is found it should likewise insert it in the DB... I am using table adpater in doing this method.
Here is the code:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim pta As New PHDSTableAdapters.productdatabaseTableAdapter
pta.Updateproduct(TextBox1.Text, ComboBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text)
pta.Fill(myds.productdatabase)
Dim lta As New PHDSTableAdapters.lotnoTableAdapter
Dim lt = lta.GetDataBylotno(TextBox5.Text)
Dim l As phaccess.PHDS.lotnoRow = lt.Rows(0)
Dim i As Integer
For i = 0 To DGV.Rows.Count - 1
For Each l In myds.lotno
Dim lot As String = DGV.Rows(i).Cells(1).Value
Dim del As Date = DGV.Rows(i).Cells(2).Value
Dim exp As Date = DGV.Rows(i).Cells(3).Value
Dim quantity As Integer = DGV.Rows(i).Cells(4).Value
Dim sup = DGV.Rows(i).Cells(5).Value
Dim disc = DGV.Rows(i).Cells(6).Value
If l.productid = TextBox5.Text Then
Dim lotnumber As String = l.lotnumber
If l.lotnumber <> lot Then
'the error occurs in the insert statement as it would create duplicates 'of the index...the index of the table is the lot number
lta.Insert(TextBox5.Text, lot, del, exp, quantity, sup, disc)
Else
lta.Updateedit(del, exp, quantity, sup, disc, lot)
lta.Fill(myds.lotno)
End If
End If
If lot = "" Then
closeform()
lta.Fill(myds.lotno)
Button3.Enabled = False
Button1.Visible = True
Button3.Visible = False
Button1.Enabled = False
Exit Sub
End If
Next
Next
End Sub
If you need anything else to help me solve this please do ask.
thank you
you can use "DataTable" to upadate DataGridView in your table
For displaying data:
Dim sql As String = "SELECT * FROM table_name"
sCommand = New SqlCommand(sql, conn)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "table_name")
sTable = sDs.Tables("table_name")
DataGridView1.DataSource = sTable
for updating:
sAdapter.Update(sTable)
i hope this helps

The select command property has not been initialized before calling 'Fill'

I am working on a Windows forms project that connects to a Microsoft Access database, reads the the file, does some math and then provides some basic statistics back. Right now I am teaching myself VB and I know the code below could be more efficient. However, right now I am just trying to make it functional.
The program filters the data it needs via sql, and there are several sql statements. I separated the code for each of the sql statements and into a subroutine so that I could call each one when the form loads and also when the user clicks a button to update. The program works fine on the form load, however, when you click the update button you get the following error on the 'odaCalls.Fill' in subroutine Count(): "The select command property has not been initialized before calling 'Fill'.
Any help is greatly appreciated. I have searched on google and tried the suggestions found there but have not found a fix.
Option Explicit On
Public Class Form1
'Count() Variables
Dim strSQL = "SELECT * FROM tblcallLog"
Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" _
& "Data Source=C:\callLogRev2_be.accdb"
Dim odaCalls As New OleDb.OleDbDataAdapter(strSQL, strPath)
Dim datCallCount As New DataTable
Dim intCount As Integer = 0
'LiveCalls() variables
Dim strSQLLive As String = "SELECT * FROM tblcallLog WHERE callLive=True"
Dim odaCallsLive As New OleDb.OleDbDataAdapter(strSQLLive, strPath)
Dim datCallLive As New DataTable
Dim intCallLiveCount As Integer = 0
Dim decCallLivePct As Decimal
'TransferCalls() variables
Dim strSQLTransfered As String = _
"SELECT * FROM tblcallLog WHERE callName LIKE '% transfer %' OR callName LIKE 'transfer%'"
Dim odaCallsTransfered As New OleDb.OleDbDataAdapter(strSQLTransfered, strPath)
Dim datCallTransfered As New DataTable
Dim intCallTransfered As Integer = 0
Dim decCallTranfered As Decimal
'SingleStaffCall() Variables
Dim strSQLSingleStaff As String = _
"SELECT * FROM tblcallLog WHERE callName LIKE '% single %' OR callName LIKE 'single%'"
Dim odaCallSingleStaff As New OleDb.OleDbDataAdapter(strSQLSingleStaff, strPath)
Dim datCallSingleStaff As New DataTable
Dim intCallSingleStaff As Integer = 0
Dim decCallSingleStaff As Decimal
'SingleStaffCallsLive() Variables
Dim strSQLSingleStaffLive As String = _
"SELECT * FROM tblcallLog WHERE callName LIKE '% single %' OR callName LIKE 'single%' AND callLive=True"
Dim odaCallSingleStaffLive As New OleDb.OleDbDataAdapter(strSQLSingleStaffLive, strPath)
Dim datCallSingleStaffLive As New DataTable
Dim intCallSingleStaffLive As Integer = 0
Dim decCallSingleStaffLive As Decimal
'CallToday() Variables
Dim strSQLToday As String = _
"SELECT * FROM tblcallLog WHERE startDate = date()"
Dim odaCallToday As New OleDb.OleDbDataAdapter(strSQLToday, strPath)
Dim datCallToday As New DataTable
Dim intCallToday As New Integer
'CallTodayLive() Variables
Dim strSQLTodayLiveCalls As String = _
"SELECT * FROM tblcallLog WHERE callLive=TRUE AND startDate = date()"
Dim odaCallTodayLive As New OleDb.OleDbDataAdapter(strSQLTodayLiveCalls, strPath)
Dim datCallTodayLive As New DataTable
Dim intCallTodayLive As New Integer
Dim decCallTodayLive As New Decimal
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Count()
LiveCalls()
TransferCalls()
SingleStaffCalls()
SingleStaffCallsLive()
CallToday()
CallTodayLive()
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
'Checks the database for updates when user pushes the update button on the static data tab.
Count()
LiveCalls()
TransferCalls()
SingleStaffCalls()
SingleStaffCallsLive()
CallToday()
CallTodayLive()
End Sub
Private Sub Count()
'database connect and call count
odaCalls.Fill(datCallCount)
odaCalls.Dispose()
intCount = datCallCount.Rows.Count
lblTotalCallsData.Text = intCount.ToString
lblTotalCallsData.Visible = True
End Sub
Private Sub LiveCalls()
'determine number of live calls
odaCallsLive.Fill(datCallLive)
odaCallsLive.Dispose()
intCallLiveCount = datCallLive.Rows.Count
lblcallsLiveData.Text = intCallLiveCount.ToString
lblcallsLiveData.Visible = True
decCallLivePct = intCallLiveCount / intCount
lblPctCallsLiveData.Text = decCallLivePct.ToString("P")
lblPctCallsLiveData.Visible = True
End Sub
Private Sub TransferCalls()
'determine the number of transfer calls
odaCallsTransfered.Fill(datCallTransfered)
odaCallsTransfered.Dispose()
intCallTransfered = datCallTransfered.Rows.Count
lblTotalTransferCallsData.Text = intCallTransfered.ToString
lblTotalTransferCallsData.Visible = True
decCallTranfered = intCallTransfered / intCount
lblPctTransferCallsData.Text = decCallTranfered.ToString("P")
lblPctTransferCallsData.Visible = True
End Sub
Private Sub SingleStaffCalls()
'determine the number of single staff calls and percentage of total
odaCallSingleStaff.Fill(datCallSingleStaff)
odaCallSingleStaff.Dispose()
intCallSingleStaff = datCallSingleStaff.Rows.Count
lblTotalSingleStaffCallData.Text = intCallSingleStaff.ToString
lblTotalSingleStaffCallData.Visible = True
decCallSingleStaff = intCallSingleStaff / intCount
lblPctSingleStaffCallsData.Text = decCallSingleStaff.ToString("P")
End Sub
Private Sub SingleStaffCallsLive()
'determine the percentage of single staff calls taken live
odaCallSingleStaffLive.Fill(datCallSingleStaffLive)
odaCallSingleStaffLive.Dispose()
intCallSingleStaffLive = datCallSingleStaffLive.Rows.Count
decCallSingleStaffLive = intCallSingleStaffLive / intCount
lblPctSingleStaffCallsLiveData.Visible = True
lblPctSingleStaffCallsLiveData.Text = decCallSingleStaffLive.ToString("P")
End Sub
Private Sub CallToday()
'determine values for todays date
odaCallToday.Fill(datCallToday)
odaCallToday.Dispose()
intCallToday = datCallToday.Rows.Count
lblTotalCallsTodayData.Text = intCallToday
lblTotalCallsTodayData.Visible = True
End Sub
Private Sub CallTodayLive()
'determine the number of live calls today
odaCallTodayLive.Fill(datCallTodayLive)
odaCallTodayLive.Dispose()
intCallTodayLive = datCallTodayLive.Rows.Count
lblCallsTodayLiveData.Text = intCallTodayLive.ToString
lblCallsTodayLiveData.Visible = True
'Statement to error correct so the database doesn't force the program to divide by zero
Try
decCallTodayLive = intCallTodayLive / intCallToday
Catch Exception As DivideByZeroException
lblPctCallsTodayLiveData.Text = "0.00%"
lblPctCallsTodayLiveData.Visible = True
Catch Exception As OverflowException
decCallTodayLive = 0
End Try
lblPctCallsTodayLiveData.Text = decCallTodayLive.ToString("P")
lblPctCallsTodayLiveData.Visible = True
End Sub
End Class
The problem is that you are disposing the dataadapters immediately after filling them.
This is why it works on form load, but not after. It would be better practice to create the and destroy the dataadapters in the methods where they are used instead of creating them on spec at the form level.