I am load data from database to my datagridview through ODBC adapter.
cmd = New Odbc.OdbcCommand(sql, cn)
adp = New Odbc.OdbcDataAdapter(cmd)
adp.Fill(ds, "temp2")
bs.DataSource = ds
DataGridView2.DataSource = bs
That way I can change and update data in database "lively".
But I have different situation now.
For changing data I have to go on grid's doubleclick to another form and when I come back I would like that my datagridview show changes in certain row.
This is what I try:
Dim fl As New dataform
With fl
.StartPosition = FormStartPosition.Manual
.aCallerLocation = Me.Location
.ShowDialog()
End With
fl = Nothing
Dim c_builder As New Odbc.OdbcCommandBuilder(adp)
Dim o As Integer
Try
o = adp.Update(ds, "temp2")
MsgBox(o)
Catch ex As Exception
MsgBox(ex.Message)
End Try
But I can't simply get it whole day! There is no exception generated but "o" is allways zero.
What do I do wrong and how to get this functionality to see changes in the row after returnimg from "dataform"?
Try this
cmd = New Odbc.OdbcCommand(sql, cn)
adp = New Odbc.OdbcDataAdapter(cmd)
Dim c_builder As New Odbc.OdbcCommandBuilder(adp)
adp.Fill(ds, "temp2")
bs.DataSource = ds
DataGridView2.DataSource = bs
and this
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dsChange As DataSet = New DataSet
'add record
If (ds.HasChanges(DataRowState.Added)) Then
dsChange = ds.GetChanges(DataRowState.Added)
Dim rowchange As Integer
rowchange = adp.Update(dsChange, "temp2")
If (rowchange > 0) Then
MessageBox.Show(rowchange.ToString() & " Record Berhasil Dimasukan")
End If
End If
'Modified record
If (ds.HasChanges(DataRowState.Modified)) Then
dsChange = ds.GetChanges(DataRowState.Modified)
Dim rowchange As Integer
rowchange = adp.Update(dsChange, "temp2")
If (rowchange > 0) Then
MessageBox.Show(rowchange.ToString() & " Record Berhasil Dihapus")
End If
End If
'Delete record
If (ds.HasChanges(DataRowState.Deleted)) Then
dsChange = ds.GetChanges(DataRowState.Deleted)
Dim rowchange As Integer
rowchange = adp.Update(dsChange, "temp2")
If (rowchange > 0) Then
MessageBox.Show(rowchange.ToString() & " Record Berhasil Diubah")
End If
End If
'Menerapkan perubahan
ds.AcceptChanges()
'Refresh(DataGrid)
DataGridView2.Refresh()
End Sub
Related
I'm trying to make an army list builder for a miniatures strategy game.
I'd like to know the correct method to read a SQL table cell value and to put it for each unit into a ComboBox.text field, but only into the field.
The ComBoBox collection items should not be modified (I need them to remain as it is). I just want the ComboBox.text value to be modified with the red framed value, and for each unit
For the record, currently, I read the others table informations and load them into the others ComboBoxes this way :
Private Sub TextBoxQuantitéUnités_Click(sender As Object, e As EventArgs) Handles TextBoxQuantitéUnités.Click
Dim connection As New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
Dim dt As New DataTable
Dim sqlquery As String
connection.Open()
sqlquery = "select * from liste1 Order By index_unité"
Dim SQL As New SqlDataAdapter(sqlquery, connection)
SQL.Fill(dt)
Dim cmd As New SqlCommand(sqlquery, connection)
Dim reader As SqlDataReader = cmd.ExecuteReader
ComboBoxNomUnités.DataSource = dt
ComboBoxNomUnités.DisplayMember = "nom_unité"
ComboBoxTypeUnités.DataSource = dt
ComboBoxTypeUnités.DisplayMember = "type_unité"
ComboBoxAbréviationUnités.DataSource = dt
ComboBoxAbréviationUnités.DisplayMember = "abréviation_unité"
ComboBoxCoutTotal.DataSource = dt
ComboBoxCoutTotal.DisplayMember = "cout_unité"
connection.Close()
End Sub
Many thanks :-)
The ComboBox.text where I want to load the cell value
The table picture with the framed value I want to load into the cell
The original ComboBox collection I want to keep
EDIT 2 :
My table structure
Your function call
A short clip of the program in order to understand my problem
As you can see, the function seems good and when I check the ComboBoxQuality text during the execution, it seems good but for some reason, it don't change...
The others Comboboxes are sync as you can see on the upper code.
Thanks in advance...
EDIT 3:
The whole code as requested :
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Sql
Public Class FormOst
Public Function GetStringFromQuery(ByVal SQLQuery As String) As String
Dim CN = New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
CN.Open()
Dim StrSql As String = SQLQuery
Dim cmdReader As SqlCommand = New SqlCommand(StrSql, CN)
cmdReader.CommandType = CommandType.Text
Dim SdrReader As SqlDataReader = cmdReader.ExecuteReader(CommandBehavior.CloseConnection)
GetStringFromQuery = ""
Try
With SdrReader
If .HasRows Then
While .Read
If .GetValue(0) Is DBNull.Value Then
GetStringFromQuery = ""
Else
If IsDBNull(.GetValue(0).ToString) Then
GetStringFromQuery = ""
Else
GetStringFromQuery = .GetValue(0).ToString
End If
End If
End While
End If
End With
CN.Close()
Catch ex As Exception
MsgBox(SQLQuery, MsgBoxStyle.Exclamation, "Error")
End Try
End Function
Private Sub TextBoListeArmées_Click(sender As Object, e As EventArgs) Handles TextBoxListeArmées.Click
Dim connection As New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
Dim dt As New DataTable
Dim sqlquery As String
connection.Open()
sqlquery = "select [nom_unité] + ' | ' + [abréviation_unité] as Unité, index_unité, abréviation_unité, type_unité, qualité_unité, cout_unité from liste1 Order By index_unité"
Dim SQL As New SqlDataAdapter(sqlquery, connection)
SQL.Fill(dt)
Dim cmd As New SqlCommand(sqlquery, connection)
ComboBoxNomUnités.DataSource = dt
ComboBoxNomUnités.DisplayMember = "Unité"
ComboBoxNomUnités.AutoCompleteMode = AutoCompleteMode.Append
ComboBoxNomUnités.AutoCompleteSource = AutoCompleteSource.ListItems
ComboBoxTypeUnités.DataSource = dt
ComboBoxTypeUnités.DisplayMember = "type_unité"
ComboBoxAbréviationUnités.DataSource = dt
ComboBoxAbréviationUnités.DisplayMember = "abréviation_unité"
ComboBoxCoutUnité.DataSource = dt
ComboBoxCoutUnité.DisplayMember = "cout_unité"
LabelListeChargéeVisible.Enabled = True
LabelListeChargée.Visible = True
connection.Close()
End Sub
Private Sub TextBoxQuantitéUnités_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBoxQuantitéUnités.KeyPress
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
End Sub
Private Sub TextBoxQuantitéUnités_TextChanged(sender As Object, e As EventArgs) Handles TextBoxQuantitéUnités.TextChanged
Try
TextBoxCoutTotal.Text = (Decimal.Parse(TextBoxQuantitéUnités.Text) * Decimal.Parse(ComboBoxCoutUnité.Text)).ToString()
Catch ex As Exception
End Try
End Sub
Private Sub ButtonEffacer_Click(sender As Object, e As EventArgs) Handles ButtonEffacer.Click
TextBoxQuantitéUnités.Text = ""
ComboBoxNomUnités.Text = ""
ComboBoxTypeUnités.Text = ""
ComboBoxQualitéUnités.Text = ""
ComboBoxAbréviationUnités.Text = ""
ComboBoxCoutUnité.Text = ""
TextBoxCoutTotal.Text = ""
End Sub
Private Sub LabelListeChargéeVisible_Tick(sender As Object, e As EventArgs) Handles LabelListeChargéeVisible.Tick
LabelListeChargée.Visible = False
LabelListeChargéeVisible.Enabled = False
End Sub
Private Sub ComboBoxNomUnités_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBoxNomUnités.SelectionChangeCommitted
Try
'' TextBoxCoutTotal.Text = (Decimal.Parse(ComboBoxCoutUnité.SelectedItem.ToString) * Decimal.Parse(TextBoxQuantitéUnités.Text)).ToString
ComboBoxQualitéUnités.Text = GetStringFromQuery("SELECT qualité_unité FROM liste1 ORDER BY index_unité")
Catch ex As Exception
End Try
End Sub
End Class
Function for retrieving your data via sql query
Public Function GetStringFromQuery(ByVal SQLQuery As String) As String
Dim CN As New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
CN.Open()
Dim StrSql As String = SQLQuery
Dim cmdReader As SqlCommand = New SqlCommand(StrSql, CN)
cmdReader.CommandType = CommandType.Text
Dim SdrReader As SqlDataReader = cmdReader.ExecuteReader(CommandBehavior.CloseConnection)
'SdrReader = cmdReader.ExecuteReader
GetStringFromQuery = ""
Try
With SdrReader
If .HasRows Then
While .Read
If .GetValue(0) Is DBNull.Value Then
GetStringFromQuery = ""
Else
If IsDBNull(.GetValue(0).ToString) Then
GetStringFromQuery = ""
Else
GetStringFromQuery = .GetValue(0).ToString
End If
End If
End While
End If
End With
CN.Close()
Catch ex As Exception
MsgBox(SQLQuery, MsgBoxStyle.Exclamation, "Error")
End Try
End Function
Retrieve data and put into your combo box text
ComboBox.Text = GetStringFromQuery("Enter Sql Query here")
Your sql query problem.
Your query select everything and you suppose to return the UOM that relate to your item
Private Sub ComboBoxNomUnités_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBoxNomUnités.SelectionChangeCommitted
Try
Dim Product as string = ComboBoxNomUnités.Text
ComboBoxQualitéUnités.Text = GetStringFromQuery("SELECT qualité_unité FROM liste1 Where Nom_Unité = '" & Product & "'")
Catch ex As Exception
End Try
End Sub
I try to add a parameters.addwithvalue.
Before change the code is like that..........
Private Sub ComboBox7_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox7.SelectedIndexChanged
Me.Cursor = Cursors.WaitCursor
MysqlConn.Close()
MysqlConn.Open()
COMMAND.CommandText = "select logo from licenses where name = '" & ComboBox7.Text & "'"
COMMAND.Connection = MysqlConn
Dim da As New MySqlDataAdapter(COMMAND)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
If IsDBNull(ds.Tables(0).Rows(c - 1)("logo")) = True Then
PictureBox6.Image = Nothing
Else
Dim bytBLOBData() As Byte = ds.Tables(0).Rows(c - 1)("logo")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
PictureBox6.Image = Image.FromStream(stmBLOBData)
End If
End If
Me.Cursor = Cursors.Default
End Sub
Now what i try this to add paramatrers.addwithValue without succes:
Private Sub ComboBox7_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox7.SelectedIndexChanged
Me.Cursor = Cursors.WaitCursor
MysqlConn.Close()
MysqlConn.Open()
'COMMAND.CommandText = "select logo from licenses where name = '" & ComboBox7.Text & "'"
COMMAND.CommandText = "select logo from licenses where name = #ComboBox7Select"
COMMAND.Parameters.AddWithValue("#ComboBox7Select", If(String.IsNullOrEmpty(ComboBox7.Text), DBNull.Value, ComboBox7.Text))
COMMAND.Connection = MysqlConn
Dim da As New MySqlDataAdapter(COMMAND)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
If IsDBNull(ds.Tables(0).Rows(c - 1)("logo")) = True Then
PictureBox6.Image = Nothing
Else
Dim bytBLOBData() As Byte = ds.Tables(0).Rows(c - 1)("logo")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
PictureBox6.Image = Image.FromStream(stmBLOBData)
End If
End If
Me.Cursor = Cursors.Default
End Sub
With error "Parameter '#ComboBox7Select' has already been defined."
What i do to change for work ??
Thanks you.
Don't store the MySqlConnection and MySqlCommand as fields in your class, don't reuse them at all. That's just a source of errors without any benefit. Create, initialize, use and dispose(Using-statement)them wherever you need them, so in this method.
You don't clear the parameters, that's why you get this error on second use.
So a simple COMMAND.Parameters.Clear() before you add it would solve the issue. But use the approach i have mentioned above:
Private Sub ComboBox7_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox7.SelectedIndexChanged
Dim ds As New DataSet()
Dim licenseNameValue As Object = DBNull.Value
If Not String.IsNullOrEmpty(ComboBox7.Text) Then licenseNameValue = ComboBox7.Text
Using mysqlConn As New MySqlConnection("ConnectionString...")
Using da As New MySqlDataAdapter("select logo from licenses where name = #licenseName", mysqlConn)
da.SelectCommand.CommandText = "select logo from licenses where name = #licenseName"
da.SelectCommand.Parameters.AddWithValue("#licenseName", licenseNameValue)
da.Fill(ds, "projectimages") ' you dont need to open/close the connection with DataAdapter.Fill
End Using
End Using
' ....
End Sub
The problem is that you are using a global variable COMMAND that you use each time the selected index changes in your combo. Either you initialize the command each time with:
COMMAND=New MySqlCommand()
Or you must clear the parameters:
COMMAND.Parameters.Clear()
COMMAND.Parameters.AddWithValue("#ComboBox7Select", If(String.IsNullOrEmpty(ComboBox7.Text), DBNull.Value, ComboBox7.Text))
But the best way is always create and dispose the MySql objects with the Using struct:
Using MysqlConn As New MySqlConnection(connString)
Using COMMAND As New MySqlCommand()
'your code
End Using
End Using
I have retrieved Product List from access database into a DataGridView. here is code:
Sub loadProductList()
Try
Using dbConn As New OleDb.OleDbConnection
dbConn.ConnectionString = dbProvider & dbSource
dbConn.Open()
Dim thisSQL As String
thisSQL = "SELECT productID, productName, productCostPrice From " & tblProduct & " WHERE productBrandID=" & CType(txtBrandName.Tag, Integer)
Dim Dadapter As New OleDbDataAdapter(thisSQL, dbConn)
Dim DSet As New DataSet
Dadapter.Fill(DSet, tblProduct)
With DataGridView1
.Columns.Clear()
.DataSource = DSet.Tables(tblProduct)
With .Columns.Item(0)
.Width = 50
.HeaderText = "Code"
.Name = "Code"
End With
Dim txtColumn As New DataGridViewTextBoxColumn
With txtColumn
.Width = 50
.HeaderText = "Qty"
.Name = "Qty"
End With
.Columns.Insert(1, txtColumn)
With .Columns.Item(2)
.Width = 490
.HeaderText = "Description"
End With
With .Columns.Item(3)
.Width = 100
.HeaderText = "Price"
.Name = "Price"
.DefaultCellStyle.Format = "N"
End With
Dim txtaColumn As New DataGridViewTextBoxColumn
.Columns.Insert(4, txtaColumn)
With .Columns.Item(4)
.Name = "Amount"
.HeaderText = "Amount"
.Width = 120
.DefaultCellStyle.Format = "N"
End With
End With
End Using
Catch ex As Exception
End Try
End Sub
Sub UpdatePurchaseItemList()
Try
Using dbConn As New OleDb.OleDbConnection
dbConn.ConnectionString = dbProvider & dbSource
dbConn.Open()
Dim thisSQL As String
thisSQL = "SELECT * FROM " & tblPurchaseItems & " WHERE PitemPID='" & txtRefID.Text & "'"
Using dbDataCmd As New OleDbCommand(thisSQL, dbConn)
Dim dbDataRead As OleDbDataReader
dbDataRead = dbDataCmd.ExecuteReader()
Do While dbDataRead.Read = True
For i As Integer = 0 To DataGridView1.Rows.Count - 1
With DataGridView1.Rows(i)
If .Cells("Code").Value = dbDataRead("PitemProductID") Then
.Cells("Qty").Value = dbDataRead("PitemProductQty")
.Cells("Price").Value = dbDataRead("PitemCost")
.Cells("Amount").Value = dbDataRead("PitemTotal")
Exit For
End If
End With
Next
Loop
End Using
End Using
Catch ex As Exception
End Try
End Sub
on form load i am calling both sub:
loadProductList()
UpdatePurchaseItemList() ' this does not update any thing
but when i call this sub on button click even it works perfectly.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
UpdatePurchaseItemList() 'it shows the updates.
End Sub
please tell me why it does not show updates?
Thanks
I'm not able to test right now, but try endedit() after you update your datagridview:
With DataGridView1.Rows(i)
If .Cells("Code").Value = dbDataRead("PitemProductID") Then
.Cells("Qty").Value = dbDataRead("PitemProductQty")
.Cells("Price").Value = dbDataRead("PitemCost")
.Cells("Amount").Value = dbDataRead("PitemTotal")
DataGridView1.EndEdit()
Exit For
End If
End With
That should 'Commits and ends the edit operation on the current cell.' as per MSDN Datagridview.EndEdit Method
ok try this trick it will automatically update the data on you're datagridview
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RefreshData()
End Sub
Private Sub RefreshData()
Dim da As OleDbDataAdapter
Dim ds As New DataSet
If Not cnn.State = ConnectionState.Open Then
'open connection
cnn.Open()
End If
da = New OleDb.OleDbDataAdapter("Select * FROM tblPurchaseItems", cnn)
'Dim dt As New DataSet
'fill data to datatable
da.Fill(ds)
'offer data in data table into datagridview
Me.DataGridView1.DataSource = ds.Tables(0)
Me.DataGridView1.Refresh()
'close connection
cnn.Close()
End Sub
and then copy and paste RefreshData() before the end of your, add,edit,delete sub statement
I am trying to display sql database table data in a list view in my vb application. I have used the following code
Public Class Form1
Dim conn As SqlClient.SqlConnection
Dim cmd As SqlClient.SqlCommand
Dim da As SqlClient.SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
conn = New SqlClient.SqlConnection("Data Source=AYYAGARI-PC\WINCC;Initial Catalog=anand;Integrated Security=True")
conn.Open()
Dim strQ As String = String.Empty
strQ = "SELECT * FROM [anand].[dbo].[WINCC] ORDER BY [dateandtime]"
cmd = New SqlClient.SqlCommand(strQ, conn)
da = New SqlClient.SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
Me.ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
Try
Call Timer1_Tick(sender, e)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
For Each i As ListViewItem In ListView1.SelectedItems
ListView1.Items.Remove(i)
Next
Try
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
The problem with the above code is that whenever i update the table data in sql (inserting or deleting data), the same doesnt get updated in list view. Kindly help me out with this.
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
conn = New SqlClient.SqlConnection("Data Source=AYYAGARI-PC\WINCC;Initial Catalog=anand;Integrated Security=True")
conn.Open()
Dim strQ As String = String.Empty
strQ = "SELECT * FROM [anand].[dbo].[WINCC] ORDER BY [dateandtime]"
cmd = New SqlClient.SqlCommand(strQ, conn)
da = New SqlClient.SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
Me.ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
Try
Call Timer1_Tick(sender, e)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Try to add this code again to your button which made insert or update.
UPDATE
I give you another tips, that wont make your code so long and wasted memory or capacity..
Try to insert all the code to new sub, e.g :
private sub mycode
msgbox("Hello World")
end sub >> This code won't work when you debug, cause it just like a stored code, so need to be called to make it work
Private sub Form_load...... > E.g this is your form load code
call mycode >> Called the code above
end sub >> when you debug, your form will auto called the mycode
Sub CboSO_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles CboSO.DropDown
If functionmode = "UPDATE" Then
Dim daProp2 As New OdbcDataAdapter()
Dim dsProp2 As New DataSet()
Dim qryProp2 As String
qryProp2 = "SELECT num FROM so WHERE scn = '" & txtSCN.Text & " '"
daProp2.SelectCommand = New OdbcCommand(qryProp2, conn)
Dim cb2 As OdbcCommandBuilder = New OdbcCommandBuilder(daProp2)
daProp2.Fill(dsProp2, "so")
Dim dtRbt As DataTable = dsProp2.Tables("so")
Try
If dsProp2.Tables(0).Rows.Count > 0 Then
CboSO.DropDownStyle = ComboBoxStyle.DropDownList
CboSO.DataSource = dsProp2
CboSO.DisplayMember = "num"
End If
Catch ex As OdbcException
MsgBox(ex.ToString)
Finally
conn.Close()
End Try
End If
End Sub
Assign the DataTable object reference.
CboSO.DataSource = dtRbt
CboSO.DisplayMember = "num"