Read a SQL table cell value and only change a ComboBox.text without changing the ComboBox collection items - sql

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

Related

Select from query not functioning

I just want to search data in my db but it is not functioning even if the data that I input in the textbox and comboBox has the correct data it keep show the else statement. it should be the else
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
searchWanted()
End Sub
Public Sub searchWanted()
Dim connString111 As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=bin\Debug\record.accdb"
MyConn111 = New OleDbConnection
MyConn111.ConnectionString = connString111
Try
Dim mySQLCommand As New OleDbCommand("select from * mostwanted where FIRSTNAME = #b0 and MIDDLENAME = #b1 and LASTNAME = #b2 and QLFR = #b3", MyConn111)
mySQLCommand.Parameters.AddWithValue("#b0", FIRSTNAMETextBox.Text)
mySQLCommand.Parameters.AddWithValue("#b1", MIDDLENAMETextBox.Text)
mySQLCommand.Parameters.AddWithValue("#b2", LASTNAMETextBox.Text)
mySQLCommand.Parameters.AddWithValue("#b3", QLFRComboBox.SelectedItem)
Dim da111 As New OleDbDataAdapter(mySQLCommand)
Dim table As New DataTable()
If table.Rows.Count() > 0 Then
MessageBox.Show("This Person is Wanted")
Dim picturedata As [Byte]() = table.Rows(0)(15)
Using ms As New MemoryStream(picturedata)
PHOTOPictureBox.Image = Image.FromStream(ms)
End Using
Else
MessageBox.Show("This Person is CLEAN")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Parameters.AddWithValue: Parameter has already been defined

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

How to save changes from DataGridView to the database?

I would like to save the changes made to a DataGridView into the database MS SQL CE,
but i can't, the changes are not saved to the database....
This the code (VB.net):
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) handles MyBase.Load
Dim con As SqlCeConnection = New SqlCeConnection(#"Data Source=C:\Users\utente\Documents\test.sdf")
Dim cmd As SqlCeCommand = New SqlCeCommand("SELECT * FROM mytable", con)
con.Open()
myDA = New SqlCeDataAdapter(cmd)
Dim builder As SqlCeCommandBuilder = New SqlCeCommandBuilder(myDA)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "MyTable")
DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
End Sub
Private Sub edit_rec()
Dim txt1, txt2 As String
Dim indice As Integer = DataGridView1.CurrentRow.Index
txt1 = DataGridView1(0, indice).Value.ToString '(0 is the first column of datagridview)
txt2 = DataGridView1(1, indice).Value.ToString '(1 is the second) MsgBox(txt1 + " " + txt2)
'
DataGridView1(0, indice).Value = "Pippo"
DataGridView1(1, indice).Value = "Pluto"
'
Me.Validate()
Me.myDA.Update(Me.myDataSet.Tables("MyTable"))
Me.myDataSet.AcceptChanges()
'
End Sub
Thank you for any suggestion.
You need to use myDA.Update, that will commit the changes. This is because any changes that you are making are made in the local instance of that dataset. And therefore disposed of just like any other variable.
... I can see that in your edit_rec sub, but what is calling that - there is nothing in the code that you have posted.
A little late perhaps.
In the Form load event, you open and close the connection.
And furthermore, all are local variables who loose any value or data when leaving the sub
Public Class Form1
Dim con As SqlCeConnection
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con = New SqlCeConnection(#"Data Source=C:\Users\utente\Documents\test.sdf")
Dim cmd As SqlCeCommand = New SqlCeCommand("SELECT * FROM mytable", con)
con.Open()
myDA = New SqlCeDataAdapter(cmd)
Dim builder As SqlCeCommandBuilder = New SqlCeCommandBuilder(myDA)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "MyTable")
DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
cmd.Dispose()
End Sub
***Put the closing of connection here instead or somewhere else suitable when you don't use it anymore***
Private Sub Form1_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
con.Close()
con = Nothing
End Sub
Private Sub edit_rec()
Dim txt1, txt2 As String
Dim indice As Integer = DataGridView1.CurrentRow.Index
txt1 = DataGridView1(0, indice).Value.ToString '(0 is the first column of datagridview)
txt2 = DataGridView1(1, indice).Value.ToString '(1 is the second) MsgBox(txt1 + " " + txt2)
'
DataGridView1(0, indice).Value = "Pippo"
DataGridView1(1, indice).Value = "Pluto"
'You code to update goes here and not in my scope of answer
End Sub
End Class
I think you want to add # with your connection string
SqlConnection con;
con = New SqlConnection(#"Data Source=C:\Users\utente\Documents\test.sdf");

ListView in VB.NET (VS 2010)

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

Database record search with combo box VB.NET

I try to search data records in sql database using cmbo box. It shows error "The multi-part identifier "System.Data.DataRowView" could not be found" after this "Incorrect Syntax near'='". My code is given below.
Private Sub BTNEDIT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNEDIT.Click
refreshComboBox()
CMBID.SelectedText = "Select"
End Sub
Private Sub refreshComboBox()
getConnect()
Try
Conn.Open()
Dim strSQL As String = "SELECT * FROM EMPLOYEE ORDER BY EMP_ID ASC"
Dim da As New SqlDataAdapter(strSQL, Conn)
Dim ds As New DataSet
da.Fill(ds, "EMPLOYEE")
CMBID.DataSource = ds.Tables(0)
CMBID.DisplayMember = "EMP_ID"
CMBID.ValueMember = "ID"
CMBID.SelectedValue = 0
CMBID.Invalidate()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Conn.Close()
End Try
End Sub
Private Sub CMBID_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CMBID.SelectedIndexChanged
Dim gend As String
getConnect()
Dim strSQL As String = "SELECT * FROM EMPLOYEE WHERE EMP_ID=" & CMBID.Text & ""
Try
Dim da As SqlDataAdapter = New SqlDataAdapter(strSQL, Conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "EMPLOYEE")
Dim dt As DataTable = ds.Tables("EMPLOYEE")
Dim row As DataRow
For Each row In dt.Rows
ID.Text = row("ID")
TXTNAME.Text = row("EMP_NAME")
TXTFNAME.Text = row("EMP_FNAME")
gend = row("EMP_GENDER")
If gend = "MALE" Then
RBMALE.Checked = True
RBFEMALE.Checked = False
ElseIf gend = "FEMALE" Then
RBFEMALE.Checked = True
RBMALE.Checked = False
End If
DTPEMPDOB.Value = row("EMP_DOB")
TXTCASTE.Text = row("EMP_CAST")
CMBDEPT.Text = row("EMP_DEPART")
CMBDESIG.Text = row("EMP_DESIG")
DTPEMPDOJ.Value = row("EMP_DOJ")
MTXTSAL.Text = row("EMP_SALARY")
MTXTPFESI.Text = row("EMP_PF_ESI")
TXTBRANCH.Text = row("EMP_BRANCH")
MTXTCONTACT.Text = row("EMP_CONTACT")
RTXTADDRESS.Text = row("EMP_ADDRESS")
Next row
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Conn.Close()
End Try
End Sub
Please try to check my code and give me solution.
Dim strSQL As String = "SELECT * FROM EMPLOYEE ORDER BY EMP_ID ASC"
Dim da As New SqlDataAdapter(strSQL, Conn)
Dim ds As New DataSet
da.Fill(ds, "EMPLOYEE")
CMBID.DataSource = ds.Tables(0)
CMBID.DisplayMember = "EMP_ID"
CMBID.ValueMember = "ID"
CMBID.SelectedValue = Nothing
//CMBID.Invalidate()
Private Sub CMBID_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CMBID.SelectedIndexChanged
{
If clientComboBox.SelectedValue Is Nothing Then
Return
End If
If CMBID.SelectedValue.toString() = "System.Data.DataRowView" Then
Return
End If
//Do stuff
}