datagridview not updating automatically in vb.net - vb.net

The datagirdview is not updating after immediate in inserting records.
Private Sub updatedgv()
Using congv As OleDbConnection = New OleDbConnection("Provider=microsoft.jet.oledb.4.0;data source=..\library.mdb")
Dim strgv As String = "select * from NormalTransaction where RegNo='" & txt_RegisterNo.Text & "'"
Dim cmdgv As OleDbCommand = New OleDbCommand(strgv, congv)
Dim sdagv As OleDbDataAdapter = New OleDbDataAdapter(cmdgv)
Dim dsgv As DataSet = New DataSet("gvSet")
sdagv.Fill(dsgv)
DataGridView1.DataSource = dsgv
DataGridView1.DataMember = dsgv.Tables(0).TableName
End Using
End Sub
please help me to solve this.

Related

How to call the datatable fill code without double in vb.net

How to call the datatable fill code without double in vb.net?.
in the code below you might see I wrote back the fill datatable code if there is a solution without me writing it back in "GenerateReport()". Please Recommend.
Thanks
Private WithEvents dt As New DataTable
Public Sub fillDataGridView1()
dt = New DataTable
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
da.Dispose()
Dim totalColumn As New DataColumn()
totalColumn.DataType = System.Type.GetType("System.Double")
totalColumn.ColumnName = "Total"
totalColumn.Expression = "[CIA]*[QTY]*(1-[DPR]/100)"
dt.Columns.Add(totalColumn)
Me.grid.DataSource = dt
Me.grid.Refresh()
End Using
End Using
End Using
End Sub
Private Sub GenerateReport()
KtReport1.Clear()
'the code below actually already exists but I reuse it
dt = New DataTable
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
Dim dtCloned As DataTable = dt.Clone()
dtCloned.Columns("CIA").DataType = GetType(String)
For Each row As DataRow In dt.Rows
dtCloned.ImportRow(row)
Next row
KtReport1.AddDataTable(dtCloned)
The issue is that you are essentially duplicating code despite the fact that you have a variable setup to hold the filled DataTable at the Form level.
What I would suggest doing is creating a function that returns the filled DataTable, then at the top of your two existing methods do a null check against the Form level variable.
Take a look at this example:
Private _dt As DataTable
Private Function GetAndFillDataTable() As DataTable
Dim dt As New DataTable()
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
da.Dispose()
Dim totalColumn As New DataColumn()
totalColumn.DataType = System.Type.GetType("System.Double")
totalColumn.ColumnName = "Total"
totalColumn.Expression = "[CIA]*[QTY]*(1-[DPR]/100)"
dt.Columns.Add(totalColumn)
Return dt
End Using
End Using
End Using
End Function
Private Sub FillDataGridView1()
If (_dt Is Nothing) Then
_dt = GetAndFillDataTable()
End If
grid.DataSource = _dt
grid.Refresh()
End Sub
Private Sub GenerateReport()
If (_dt Is Nothing) Then
_dt = GetAndFillDataTable()
End If
Dim dtCloned As DataTable = _dt.Clone()
dtCloned.Columns("CIA").DataType = GetType(String)
For Each row In _dt.Rows
dtCloned.ImportRow(row)
Next row
KtReport1.AddDataTable(dtCloned)
End Sub

Update edited ComboBox items in database instead of adding them

I have a combobox named "Barcode", I fill it from database like this:
Sub fillIBarcode()
Barcode.DataSource = Nothing
Barcode.Items.Clear()
Dim adp As New SqlClient.SqlDataAdapter("Select distinct Barcode from Items where ItemCode=N'" & (ItemsDGV.CurrentRow.Cells(0).Value) & "'", SQlconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
'=====================================================
For I = 0 To dt.Rows.Count - 1
Barcode.Items.Add(dt.Rows(I).Item("Barcode"))
Barcode.SelectedIndex = 0
Next
End Sub
And it displays like that:
When the user edits and changes any numbers in the combobox and clicks the "Edit" button, how to submit this change and update the combobox items list immediately in the database?
I tried:
Private Sub Editbtn_Click(sender As Object, e As EventArgs) Handles Editbtn.Click
Dim cmdd As New SqlClient.SqlCommand
cmdd.Connection = SQlconn
cmdd.CommandText = "delete from Items where ItemCode=N'" & (ItemCode.Text) & "'"
cmdd.ExecuteNonQuery()
Dim sql = "select * From Items where ItemCode=N'" & (ItemCode.Text) & "'"
Dim adp As New SqlClient.SqlDataAdapter(sql, SQlconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
If dt.Rows.Count = 0 Then
For i = 0 To Barcode.Items.Count - 1
Dim dr = dt.NewRow
dr!ItemCode = ItemCode.Text
dr!Barcode = Barcode.Items(i).ToString
dt.Rows.Add(dr)
Next
Dim cmd As New SqlClient.SqlCommandBuilder(adp)
adp.Update(dt)
End If
End Sub
But it adds the new value, instead of updating the existing one.
I mean it added three barcodes, the original two, and the new edited one.
use SQL UPDATE QUERY :
you must conserve dt across form event to keep old value
dt has same index as combobox
declare dt as global in front of form code
Dim dt as datatable
in Sub fillIBarcode() remove DIM
dt = ds.Tables(0)
and in event handler execute an UPDATE query with ref to combobox selectedIndex:
Private Sub Editbtn_Click(sender As Object, e As EventArgs) Handles Editbtn.Click
Dim cmdd As New SqlClient.SqlCommand
cmdd.Connection = SQlconn
cmdd.CommandText = "UPDATE Items SET ItemCode=N'" & (ItemCode.Text) & "' WHERE ItemCode = N'" & dt.rows(Barcode.SelectedIndex).Item("Barcode") & "'"
cmdd.ExecuteNonQuery()
'update dt
dt.rows(Barcode.SelectedIndex).Item("Barcode") = ItemCode.Text
End Sub

How to create a query in Visual Studio 2013 using Visual Basic

I have the following code and through debugging the problem begins at the While loop. I am trying to retrieve information from 2 tables and insert it into the table created. The information is not being inserted into the table and I am getting blank rows.
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=M:\ICT-Group-Project\DeepBlueProject\DeepBlueProject\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT CruiseID, RouteID FROM Cruise WHERE CruiseID =?"
Dim RouteQuery As String = "SELECT RouteName FROM Route WHERE RouteID =?"
Dim cmd As OleDbCommand = New OleDbCommand(CruiseQuery, cn)
Dim cmd2 As OleDbCommand = New OleDbCommand(RouteQuery, cn)
cmd.Parameters.AddWithValue("?", Route_Txt.Text)
Dim reader As OleDbDataReader
reader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "Route"
While reader.Read()
Dim rID As String = reader("RouteID").ToString()
cmd2.Parameters.AddWithValue("?", rID)
Dim reader2 As OleDbDataReader = cmd2.ExecuteReader()
'MsgBox(reader.GetValue(0) & "," & reader.GetValue(1))
row = reader("CruiseID") & "," & reader2("RouteName")
RCTable.Rows.Add(row)
cmd.ExecuteNonQuery()
reader2.Close()
End While
reader.Close()
cn.Close()
End Sub
End Class
If I understand your tables structure well then you could just run a single query extracting data from the two table and joining them in a new table returned by the query
Dim sql = "SELECT c.CruiseID c.CruiseID & ',' & r.RouteName as Route " & _
"FROM Cruise c INNER JOIN Route r ON c.RouteID = c.RouteID " & _
" WHERE c.CruiseID = #cruiseID"
Dim cmd As OleDbCommand = New OleDbCommand(sql, cn)
cmd.Parameters.Add("#cruiseID", OleDbType.Int).Value = Convert.ToInt32(Route_Txt.Text)
Dim RCTable = new DataTable()
Dim reader = cmd.ExecuteReader()
reader.Load(RCTable)
At this point the RCTable is filled with the data coming from the two tables and selected using the Route_Txt textbox converted to an integer. If the CruiseID field is not a numeric field then you should create the parameter as of type OleDbType.VarWChar and remove the conversion to integer
Try simplifying your query.
Dim CruiseRouteQuery As String = "SELECT C.CruiseID, C.RoutID, R.Routename FROM Cruise C LEFT JOIN Route R ON C.RouteID = R.RoutID WHERE CruiseID =?"
Also, please let us know what errors you are getting.

Error "Child list for field [Sheet1$] cannot be created" when loading data from excel to datagridview

I am trying to fill the DataGridView (grvExcelData in this case) with data from an excel file. But I am getting the following error:
"Child list for field [Sheet1$] cannot be created"
Below is my code fragment where I am trying to fill the data grid view. Also I am using Visual Studio 2010 for programming
Thanks for your help in advance
Public Sub fillgrid()
Dim conn1 As String
conn1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filenamepath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
Dim connection As OleDbConnection = New OleDbConnection(conn1)
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection)
Dim ds As DataSet = New DataSet()
Dim emptyfile As String = "The file does not have any records for inserting."
Dim selectCmd As OleDbCommand = New OleDbCommand()
selectCmd.Connection = connection
selectCmd.CommandText = "SELECT * FROM [Sheet1$]"
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
da.SelectCommand = selectCmd
Dim dsCounter As Integer = da.Fill(ds, "[Sheet1$]")
If dsCounter = 0 Then
MessageBox.Show(emptyfile, "dsCounter")
End If
grvExcelData.DataSource = ds
grvExcelData.DataMember = "Sheet1"
grvExcelData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
da.Dispose()
If connection.State = ConnectionState.Open Then
connection.Close()
connection.Dispose()
End If
End Sub
Change
grvExcelData.DataMember = "Sheet1"
to
grvExcelData.DataMember = "[Sheet1$]"

Vb.Net and CSV files

I have a VB.Net app that should enable the user to import CSV file into the datagrid (which it does) and then update those rows to a table in Oracle.
Here is what I have so far but it doesn't seem to work neither throw an error.
Private Sub Update_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Update.Click
MsgBox("Saving...")
Dim table As New DataTable()
Dim BindingSource As New BindingSource()
BindingSource.DataSource = table
table.Columns.Add("ORDER_NO")
table.Columns.Add("LINE_ITEM_NO")
table.Columns.Add("CONTRACT")
table.Columns.Add("PART_NO")
table.Columns.Add("QTY_REQUIRED")
table.Columns.Add("QTY_PER_ASSEMBLY")
table.Columns.Add("RELEASE_NO")
table.Columns.Add("SEQUENCE_NO")
table.Columns.Add("ORDER_CODE")
table.Columns.Add("PART_OWNERSHIP")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\User\Desktop\solution.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
parser.ReadLine()
Dim sConnectionString As String = "Data
Source=MYSERVER.COM;User ID=MYNAME;Password=MYPASSWD;"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOC_TAB(ORDER_NO,
LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY,
RELEASE_NO,SEQUENCE_NO,ORDER_CODE,PART_OWNERSHIP) VALUES (#ORDER_NO,
#LINE_ITEM_NO,#CONTRACT,#PART_NO,#QTY_REQUIRED,#QTY_PER_ASSEMBLY,#RELEASE_NO,#SEQUENCE_NO,#ORDER_CODE,#PART_OWNERSHIP)"
Using conn As New OracleClient.OracleConnection(sConnectionString)
Dim adapter As New OracleDataAdapter
Dim cmd As New OracleClient.OracleCommand()
cmd.Connection = conn
cmd.Connection.Open()
cmd.CommandText = strSql
adapter.InsertCommand = New OracleCommand(strSql, conn)
adapter.UpdateCommand = cmd
adapter.Update(table)
'--cmd.ExecuteReader()
cmd.Connection.Close()
MsgBox("Saved! Kindly check your Shop order!")
DataGridView1.DataSource = Nothing
End Using
End Sub
Now I have brought it down to inserting records in the table, but problem is it only parses the first column in the row.
So all suppose 6 columns in the table are updated with values from the first field in the CSV.
MsgBox("Saving...")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\nUser\Desktop\solution.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
Dim i As Integer
For i = 0 To DataGridView1.RowCount - 1
Dim CurrentField = parser.ReadFields()
'--parser.ReadLine()
Dim sConnectionString As String = "Data Source=MYSERVER.COM;User ID=MYUSER;Password=MYPASSWD;"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOCT(ORDER_NO, LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY) VALUES (:ORDER_NO, :LINE_ITEM_NO,:CONTRACT,:PART_NO,:QTY_REQUIRED,:QTY_PER_ASSEMBLY)"
Using conn As New OracleClient.OracleConnection(sConnectionString)
Using cmd As New OracleClient.OracleCommand()
Dim adapter As New OracleDataAdapter
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSql
cmd.Parameters.AddWithValue("ORDER_NO", CurrentField(i))
cmd.Parameters.AddWithValue("LINE_ITEM_NO", CurrentField(i))
cmd.Parameters.AddWithValue("CONTRACT", CurrentField(i))
cmd.Parameters.AddWithValue("PART_NO", CurrentField(i))
cmd.Parameters.AddWithValue("QTY_REQUIRED", CurrentField(i))
cmd.Parameters.AddWithValue("QTY_PER_ASSEMBLY", CurrentField(i))
cmd.CommandText = strSql
adapter.InsertCommand = New OracleCommand(strSql, conn)
adapter.UpdateCommand = cmd
'adapter.Update(table)
cmd.ExecuteNonQuery()
cmd.Connection.Close()
DataGridView1.DataSource = Nothing
End Using
End Using
Next
Never used oracle so please ignore me if I'm being stupid.
Have you tried conn.Connect() rather than cmd.Connection.Open()?
I don't understand the part of your code that create a DataTable and add columns.
It's not used anywhere, so is not related to your issue.
Let's look at code relating data connection
' If I remember well, the parameters in an oracle statement are prefixed by a ":"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOC_TAB(ORDER_NO," +
"LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY, " +
"RELEASE_NO,SEQUENCE_NO,ORDER_CODE,PART_OWNERSHIP) VALUES (:ORDER_NO, " +
":LINE_ITEM_NO,:CONTRACT,:PART_NO,:QTY_REQUIRED,:QTY_PER_ASSEMBLY, " +
":RELEASE_NO,:SEQUENCE_NO,:ORDER_CODE,:PART_OWNERSHIP)"
' Connection and Command are Disposable, so use `Using` around them
Using conn As New OracleClient.OracleConnection(sConnectionString)
Using cmd As New OracleClient.OracleCommand()
Dim adapter As New OracleDataAdapter
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSql
' Now you need to add the parameters to your command
' One parameter for each column used in the insert statement
' I suppose that values for the paramenter are in the current line from your CSV
cmd.Parameters.Add("ORDER_NO", OracleType.VarChar).Value = parser[index_of_orderNumber_Text])
' .... other parameters to be added....
' Now you can execute the INSERT statement directly with your command
cmd.ExecuteNonQuery()
End Using
And, as last thing, the OracleClient namespace has been deprecated by Microsoft, so you should try to replace with ODP directly from Oracle.