Select last record added/updated in dgv - vb.net

How to select the last record which is added or updated in datagridview
This is how i add
Insert into table (Name, AddDate) values ('" & Name & "', '" & Date.Now & "')"
After adding the record i refresh dgv
("Select * from table")
Form1.DGV.DataSource = SQLDataset1.Tables(0)
And this is how i update record
("Update table Set Name='" & txtT.Text & "' , DateEdit='" & Date.Now & "' Where Town= '" & txtT.Text & "'")
Edit :
Public Sub addIt(Name As String)
Try
Dim addStr As String = "Insert into tableName (Name, AddDate) values ('" & Name & "', '" & Date.Now & "')"
sqlcon.Open()
SqlCom = New SqlCommand(addStr, sqlcon)
SqlCom.ExecuteNonQuery()
sqlcon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'Buton click event
If Len(town) >= 3 Then
sql.addIt(town)
Msgbox("Added")
sql.resetDGV()
End If
Public Sub resetDGV()
sqlquery("Select * from tableName")
Form1.dgv.DataSource = SQLDataset.Tables(0)
End Sub

There are easier ways outside in the www. But this is the shortest so....
Public Sub addIt(Name As String) as int
Dim insertedID as int = -1
Try
Dim addStr As String = "Insert into tableName (Name, AddDate) OUTPUT INSERTED.ID values ('" & Name & "', '" & Date.Now & "')"
sqlcon.Open()
SqlCom = New SqlCommand(addStr, sqlcon)
returnValue = Convert.ToInt32(SqlCom.ExecuteScalar())
sqlcon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
return insertedID
End Sub
If Len(town) >= 3 Then
Dim insertedID as int = sql.addIt(town)
If insertedID = -1 Then return
Msgbox("Added")
sql.resetDGV()
'Select
SelectLastInsertedRow(insertedID)
End If
Public Sub resetDGV()
sqlquery("Select * from tableName")
Form1.dgv.DataSource = SQLDataset.Tables(0)
End Sub
Private Sub SelectLastInsertedRow(id as int)
For Each row as DataGridViewRow in dgv.Rows
'Check if row belongs to the ID
if(row == id) Then
'Select
row.Select = true
End if
End For
End Sub
This code is not tested. But it should work :P

Related

I am facing an issue during inserting data through datagrid in database

when i insert data through datagrid in a database data's are inserting but an additional blank row is also coming in the data base
My Code:-
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con()
Dim SNo As String
Dim Name As String
Dim Address As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
If Me.DataGridView1.Rows.Count = 0 Then
Exit For
End If
SNo = Me.DataGridView1.Rows(i).Cells(0).Value
Name = Me.DataGridView1.Rows(i).Cells(1).Value
Address = Me.DataGridView1.Rows(i).Cells(2).Value
Dim sql As String = "insert into Customer(SNo,Name,Address)values('" & SNo & "','" & Name & "','" & Address & "')"
cmd = New SqlCommand(sql, cn)
cmd.ExecuteNonQuery()
Next
MsgBox("Inserted")
cn.Close()
End Sub
Execute the loop till Datagridview1.rows.count-2
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 2
If Me.DataGridView1.Rows.Count = 0 Then
Exit For
End If
SNo = Me.DataGridView1.Rows(i).Cells(0).Value
Name = Me.DataGridView1.Rows(i).Cells(1).Value
Address = Me.DataGridView1.Rows(i).Cells(2).Value
Dim sql As String = "insert into Customer(SNo,Name,Address)values('" & SNo & "','" & Name & "','" & Address & "')"
cmd = New SqlCommand(sql, cn)
cmd.ExecuteNonQuery()
Next

insert and update in vb.net with access index out of range

i have application i want it to do
1- insert the first statement .
2-get the (maxid) of the invoice
3-insert the detail of the invoice with the Id .
it give me this error
index out of range .
Private Sub insert()
Dim invoiceday As Date = Today
Dim userid As Integer
Dim clientid As Integer
Dim note As String
If clients.Visible = True Then
userid = 1
clientid = 2
note = "cash"
Else
userid = 2
clientid = 6
note = "credit"
End If
Dim query1 As String = " insert into invoices([purchasedate],clientid,[Note],userID,total,disq) Values ( '" & CDate(invoiceday) & "','" & clientid & "','" & note & "','" & userid & "','" & totalprice.Text & "','" & txtdis.Text & "')"
samselect2(query1)
Dim maxinvoice As Integer
maxinvoice = invoiceid()
For Each row As DataGridViewRow In dvsale.Rows
Dim query As String = " insert into invoicede(invoiceid,barcode,doaname,Qty,Price,qtyprice) Values ('" & maxinvoice + 1 & "','" & row.Cells("barcode").Value & "','" & row.Cells("doaname").Value & "','" & row.Cells("qty").Value & "','" & row.Cells("price").Value & "','" & row.Cells("tqty").Value & "')"
samselect2(query)
Next
End Sub
this the class of the samselect2
Public Sub samselect2(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
End Try
con.Close()
da.Dispose()
End Sub
and the invoiceid max number
Private Function invoiceid()
checkConnection()
Dim strQ As String = "SELECT max(invoiceID)as MaxIDbatch from invoices "
Dim cmdQ As OleDbCommand = New OleDbCommand(strQ, con)
Dim result = cmdQ.ExecuteScalar()
If result IsNot Nothing Then
Dim x As Integer = 0
Return x
Else
Return result
End If
End Function
Although I don't fully understand your question, I notice a couple things: 1) It appears that InvoiceID is not an auto-incrementing identity field, and it probably should be. (Check out "Is Identity".) If it were, you could insert and specify all fields except that one, and the number would increment automatically. 2) In your for...each, you are not increasing maxinvoice at all with each iteration through the loop. Although you're using maxinvoice+1, it will still be the same number each time.
Still, all of that should be unnecessary if you make InvoiceID an identity field.

vb.net Read and write data to ms database using Odbc(ERROR)

When I try to run the program, an error shows " ERROR[07002][Microsoft][ODBC MICROSOFT ACCESS DRIVER] TOO FEW PARAMETERS.EXPECTED 1" USING THIS CONNECTION.
Public Sub open_connection ()
Try
con = New OdbcConnection("dsn = LocalDB")
con.Open()
End try
Catch ex As Exception
MsgBox(ex.message)
End sub
Problems occurs when inserting and reading..
sSql = "select * from Faculty where RFID='" & txtrfid.Text & "'"
Dim cmd As New OdbcCommand(sSql, con)
Dim dr As OdbcDataReader = cmd.ExecuteReader()
If dr.HasRows Then
dr.Read()
txtfname.Text = dr("fname").ToString()
txtlname.Text = dr("lname").ToString()
txtid.Text = dr("STID").ToString()
txtposition.Text = dr("Pstion").ToString()
txtsubject.Text = dr("Subject").ToString()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
dr.Close()
sSql = " SELECT TOP 1 flag_inout FROM Attendance where faculty_id = #StId ORDER BY Attendance_id DESC"
Dim pcmd As New OdbcCommand(sSql, con)
pcmd.Parameters.AddWithValue("#StId", txtid.Text)
Dim pdr As OdbcDataReader = pcmd.ExecuteReader()
While pdr.Read()
TextBox1.Text = pdr("flag_inout").ToString()
End While
If TextBox1.Text = "IN" Then
TextBox1.Text = "OUT"
ElseIf TextBox1.Text = "OUT" Then
TextBox1.Text = "IN"
ElseIf TextBox1.Text = Nothing Then
TextBox1.Text = "IN"
End If
pdr.Close()
'Check Duplicate
'If txtfname.Text.Length = 0 Then
' Return
'End If
'If Not CheckDateDuplicate() Then
' MessageBox.Show("Already Saved on this Date")
' Return
'End If
sSql = "insert into Attendance (faculty_id, faculty_Fname,faculty_Lname,[Position],Subject, attendance_date, attendance_time, flag_inout) values('" & txtid.Text & "','" & txtfname.Text & "','" & txtlname.Text & "','" & txtposition.Text & "','" & txtsubject.Text & "','" & DateTimePicker1.Value.Date & "','" & TimeOfDay.ToShortTimeString & "','" & TextBox1.Text & "')"
Dim xcmd As New OdbcCommand(sSql, con)
If xcmd.ExecuteNonQuery() > 0 Then
'MessageBox.Show("ATTENDANCE SAVED")
txtrfid.Text = ""
'txtid.Text = ""
'txtfname.Text = ""
'txtlname.Text = ""
'txtposition.Text = ""
'txtsubject.Text = ""
txtrfid.Focus()
Dtagrid()
End If
If TextBox1.Text = "IN" Then
lblinuse.Visible = True
lblvacant.Visible = False
lbllstuser.Visible = False
lblcrrntuser.Visible = True
ElseIf TextBox1.Text = "OUT" Then
lblinuse.Visible = False
lblvacant.Visible = True
lbllstuser.Visible = True
lblcrrntuser.Visible = False
'txtid.Text = ""
'txtfname.Text = ""
'txtlname.Text = ""
'txtposition.Text = ""
'txtsubject.Text = ""
'imgRetrieve.Image = Nothing
End If
End If
Dtagrid()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
CAUSE
This error occurs only with Microsoft Access when one of the column
names specified in a select statement does not exist in the table
being queried.
Resolution
Remove any invalid column names from the select statement.
Make sure that Column Name RFID exist in Faculty table and also check txtrfid has value or not

Create New Table on SQL Server with another table's schema

I have a procedure in VB.net that when ran, determines if a table exists or not. If it doesn't exist I want to create a table on SQL Server with the same schema as a local FoxPro table. Is this something that can be done?
Here is what I have so far. Right now it just grabs the Schema from a Visual Foxpro table and displays it. Not sure where to go from here. Any ideas?
Private Sub dwprm01()
Try
Dim tableName As String = "dwprm01"
Dim tableExists As Boolean = False
Dim foxConn As New OleDbConnection("Provider=vfpoledb.1;Data Source=Z:\update_dwprm01\" & tableName & ".DBF;Collating Sequence=general;")
sConn.Open()
Dim restrictions(3) As String
restrictions(2) = tableName
Dim dbTbl As DataTable = sConn.GetSchema("Tables", restrictions)
Console.WriteLine("Checking if " & tableName & " exists")
If dbTbl.Rows.Count = 0 Then
'Table does not exist
tableExists = False
Console.WriteLine(tableName & " does not exist")
Console.WriteLine()
Console.WriteLine("Creating " & tableName)
Dim fSQL = "SELECT * FROM " & tableName
Dim cmd As New OleDbCommand(fSQL, foxConn)
foxConn.Open()
Dim myReader As OleDbDataReader = cmd.ExecuteReader()
Dim schema As DataTable = myReader.GetSchemaTable()
For Each row As DataRow In schema.Rows
For Each col As DataColumn In schema.Columns
Console.WriteLine(col.ColumnName & " = " & row(col).ToString())
Next
Next
myReader.Close()
foxConn.Close()
Else
'Table exists
tableExists = True
Console.WriteLine(tableName & " exists")
End If
dbTbl.Dispose()
sConn.Close()
sConn.Dispose()
Catch ex As Exception
Console.WriteLine(ex.ToString())
End Try
End Sub
Since you've already verified the new table does note exist, you just want to execute a query like this:
SELECT TOP 0 * INTO NewTable FROM OriginalTable
That will create a new table with no rows whose structure matches your original.
I was able to finally figure this out. Here is what I had to do. The commented block will show you different rows in the tables schema. The Case statement is yet to be finished either, but you can add onto this as you run into more datatypes needing to be converted.
Imports System.Data.OleDb
Module prm01_up
Dim sConn As New OleDbConnection("Provider=SQLNCLI10;Server=;Database=;Uid=;Pwd=;")
Sub Main()
Dim foxTables() As String = {"dwprm01", "lkpbrnch", "add_me", "empmastr"}
For Each tableName As String In foxTables
seekAndCreate(tableName)
Next
Console.WriteLine()
Console.WriteLine("Press any key to continue...")
Console.ReadKey()
End Sub
Private Sub seekAndCreate(ByRef tableName As String)
Try
Dim tableExists As Boolean = False
Dim foxConn As New OleDbConnection("Provider=vfpoledb.1;Data Source=Z:\update_dwprm01\" & tableName & ".DBF;Collating Sequence=general;")
sConn.Open()
Dim restrictions(3) As String
restrictions(2) = tableName
Dim dbTbl As DataTable = sConn.GetSchema("Tables", restrictions)
Console.WriteLine("Checking if " & tableName & " exists")
If dbTbl.Rows.Count = 0 Then
'Table does not exist
tableExists = False
Console.WriteLine(tableName & " does not exist")
Console.WriteLine()
Console.WriteLine("Creating " & tableName)
Dim foxDs As New DataSet
Dim fSQL As String = "USE " & tableName
Dim fCmd As New OleDbCommand(fSQL, foxConn)
foxConn.Open()
Dim objDR As OleDbDataReader
objDR = fCmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim schemaTable = objDR.GetSchemaTable()
Dim colName As String = String.Empty
Dim colSize As String = String.Empty
Dim colDataType As String = String.Empty
Dim newDataType As String = String.Empty
Dim allColumns As String = String.Empty
Dim colPrecision As String = String.Empty
Dim colScale As String = String.Empty
Dim createTable As New OleDbCommand
'For Each x As DataRow In schemaTable.Rows
' For Each y As DataColumn In schemaTable.Columns
' Console.WriteLine(y.ColumnName)
' Next
' Console.WriteLine()
'Next
For Each myField As DataRow In schemaTable.Rows
colName = myField(0).ToString
colSize = myField(2).ToString
colDataType = myField(5).ToString
colPrecision = myField(3).ToString
colScale = myField(4).ToString
Select Case colDataType
Case "System.String"
newDataType = "varchar" & "(" & colSize & "), "
Case "System.Decimal"
newDataType = "numeric(" & colPrecision & ", " & colScale & "), "
Case "System.DateTime"
newDataType = "datetime, "
Case "System.Int32"
newDataType = "int,"
Case Else
newDataType = colDataType.ToString()
End Select
allColumns += "[" & colName & "]" & " " & newDataType
Next
Console.WriteLine(allColumns.Substring(0, allColumns.Length - 2))
createTable.Connection = sConn
createTable.CommandType = CommandType.Text
createTable.CommandText = "CREATE TABLE " & tableName & " (" & allColumns & ")"
createTable.ExecuteNonQuery()
foxConn.Close()
Else
'Table exists
tableExists = True
Console.WriteLine(tableName & " exists")
Console.WriteLine()
End If
foxConn.Dispose()
dbTbl.Dispose()
sConn.Close()
Catch ex As Exception
Console.WriteLine(ex.ToString())
End Try
End Sub
End Module

vbnet multiple combobox fill with one dataset

i have the following code to fill two comboboxes using one dataset:
Private Sub sub_cbo_type_load()
Dim ds As New DataSet
ds = cls.cbo_type()
If ds IsNot Nothing _
AndAlso ds.Tables.Count > 0 _
AndAlso ds.Tables(0).Rows.Count > 0 Then
Me.r_cbo_type.DataSource = ds.Tables(0)
Me.r_cbo_type.DisplayMember = "desc"
Me.r_cbo_type.ValueMember = "code"
Me.r_cbo_type.SelectedIndex = -1
Me.m_cbo_type.DataSource = ds.Tables(0)
Me.m_cbo_type.DisplayMember = "desc"
Me.m_cbo_type.ValueMember = "code"
Me.m_cbo_type.SelectedIndex = -1
End If
End Sub
the problems is: whenever the index is changed in one combobox, it's automatically changed in the other one too.
does anyone know how can i solve this?
thanks for your time.
Try cloning the tables:
Private Function CopyTable(ByVal sourceTable As DataTable) As DataTable
Dim newTable As DataTable = sourceTable.Clone
For Each row As DataRow In sourceTable.Rows
newTable.ImportRow(row)
Next
Return newTable
End Function
Then your data sources would be referencing different sources:
Me.r_cbo_type.DataSource = CopyTable(ds.Tables(0))
Me.m_cbo_type.DataSource = CopyTable(ds.Tables(0))
do like this
Private Sub btn_update1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_update1.Click
If MsgBox("Are you sure to update?" & "", MsgBoxStyle.YesNo, "Confirmation") = MsgBoxResult.Yes = True Then
Dim transmode As String = vbNullString
Dim byair As String = vbNullString
Dim bysea As String = vbNullString
If rb_air.Checked = True Then
transmode = "A"
byair = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
bysea = vbNullString
ElseIf rb_sea.Checked = True Then
transmode = "B"
byair = vbNullString
bysea = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
End If
Try
If con.State = ConnectionState.Closed Then con.Open()
global_command = New SqlCommand("update ytmi_finished_products set rev_ctrl_no = '" & txt_mrev.Text & "', by_air = '" & byair & "', by_sea = '" & bysea & "', transport_mode = '" & transmode & "' where REPLACE(prod_no, '-', '') +'-'+ ISNULL(CONVERT(varchar(50), prod_sx), '') + prod_lvl = '" & txt_mpart.Text & "' and cast(serial_no as numeric) = '" & txt_mserial.Text & "' and req_box_qty = '" & txt_mqty.Text & "' and remarks is null", con)
global_command.ExecuteNonQuery()
global_command.Dispose()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "Message")
mclear()
Catch ex As Exception
MsgBox("Trace No 20: System Error or Data Error!" + Chr(13) + ex.Message + Chr(13) + "Please Contact Your System Administrator!", vbInformation, "Message")
End Try
End If
End Sub