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
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'm making a search bar using SELECT query and I want to transfer the results to a DataGridView. But I always get an empty DataGridView.
Nothing is wrong with the query, I already tried to input it manually in access. What am I doing wrong in the code? Here it is:
Using conn = New OleDbConnection(connstring)
Try
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "*'"
Dim da As New OleDbDataAdapter(Sql, conn)
Dim ds As New DataSet
da.Fill(ds)
DataGridView2.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
End Using
The issue is as I stated in the comment. ADO.Net uses the % for the like to maintain consistency with most major Sql engines. But I would like to point out that your query is unsafe and subject to SQL injection so I have included an example of your code using a parameter to pass user input to the command.
Also note that the OleDbDataAdapter can be declared in a Using statement the same way you did with the OleDbConnection Note that you may however have to widen the scope of the dataset (ds) if you plan on doing other things with it.
Using conn As OleDbConnection = New OleDbConnection(connstring)
Try
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE #Product"
Using da As OleDbDataAdapter = New OleDbDataAdapter(Sql, conn)
da.SelectCommand.Parameters.Add("#Product", OleDbType.Varchar).Value = txtSearchProduct.Text & "%"
Dim ds As New DataSet
da.Fill(ds)
DataGridView2.DataSource = ds.Tables(0)
End Using
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
End Using
Like Charles has mentioned its always better to use parameters. My answer is a bit different whereas it uses a reader and not an adapter, and a datatable and not an entire dataset. An adapter should only be used if you intend to write back to the table, or typical scenarios include binding procedures. A DataSet is typically used when you have multiple tables and have a need to relate them. Also note, you most likely want a preceding % in your parameter if you want to match the string regardless of the position in the search column.
Try
Using conn = New OleDbConnection("YourConnString")
conn.Open()
Dim Cmd As New OleDbCommand("SELECT * FROM Products WHERE [Product Name] LIKE #Product", conn)
Cmd.Parameters.AddWithValue("#Product", "'%" & txtSearchProduct.Text & "%'")
Dim ProductsRDR As OleDbDataReader = Cmd.ExecuteReader
Dim DTable As New DataTable With {.TableName = "Products"}
DTable.Load(ProductsRDR)
DataGridView1.DataSource = DTable
conn.Close()
End Using
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
All you have to do is replacing the * sign with % in your Sql string, just like this:
This is your wrong Sql string:
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "*'"
Change it to this:
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "%'"
This should cover most of the common scenarios out there.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class
The is a database driven currency converter, where the program has to fetch the exchange rates from the database and display them.
This is what I've done so far.
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim sql As String
sql = "SELECT TOP 1 USD,EUR,GBP FROM dbexchangeRates WHERE Date='" & DateTimePicker1.Text.ToString & "'"
da = New OleDb.OleDbDataAdapter(sql, cnnOLEDB)
da.Fill(ds, "rates")
If ds.Tables("rates").Rows.Count > 0 Then
txtUSD.Text = ds.Tables("rates").Rows(0).Item(0).ToString
txtGBP.Text = ds.Tables("rates").Rows(0).Item(1).ToString
txtEUR.Text = ds.Tables("rates").Rows(0).Item(2).ToString
End If
End Sub
End Class
I recieve an Invalid operation exception on the
a.Fill(ds, "rates") '
What am i doing wrong?
Thank you for your time.
Try this:
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
Dim ds As New DataSet
Dim sql As String = "SELECT TOP 1 USD,EUR,GBP FROM dbexchangeRates WHERE Date= ?"
Using connection As New OleDb.OleDbConnection(strConnectionString),
command As New OleDb.OleDbCommand(sql, connection),
adapter As New OleDb.OleDbDataAdapter(command)
connection.Open()
adapter.SelectCommand.Parameters.Add("#dt", OleDb.OleDbType.Date).Value = DateTimePicker1.Value
adapter.Fill(ds, "rates")
connection.Close()
End Using
If ds.Tables("rates").Rows.Count > 0 Then
txtUSD.Text = ds.Tables("rates").Rows(0).Item(0).ToString
txtGBP.Text = ds.Tables("rates").Rows(0).Item(1).ToString
txtEUR.Text = ds.Tables("rates").Rows(0).Item(2).ToString
End If
End Sub
I haven't checked but I wonder if the method DateTimePicker1.ValueChanged is being called before cnnOLEDB has been initialised on MyBase.Load. This way the connection, command and adapter are all initialised at the same time. By implementing Using they will also be disposed.
You probably also want to do some data validation to ensure a valid date is set before calling the database with a query otherwise other exceptions could occur.
Hello everyone i need a little help. I want to populate my PictureBox picpreview from ListView but it says NotSupportedException was unhandled The given path's format is not supported.The textbox seems to be working fine but i got stuck at retrieving my image file. By the way the image is .gif
Dim sql As String
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
Dim cmd As New OleDb.OleDbCommand
Dim dr As OleDb.OleDbDataReader
Dim inc As Integer
Dim listselect As String
Private Sub get_data()
Try
lvroutine.Items.Clear()
connection()
sql = "SELECT * From tblprogram ORDER BY MUSCLEGROUP ASC"
cmd = New OleDbCommand(sql, con)
dr = cmd.ExecuteReader
While dr.Read
Dim lv As ListViewItem = lvroutine.Items.Add(dr("MUSCLEGROUP"))
With lv.SubItems
.Add(dr("EXERCISENAME"))
.Add(dr("EQUIPMENT"))
.Add(dr("PREVIEW"))
End With
End While
con.Close()
Catch ex As Exception
Exit Try
End Try
End Sub
Private Sub view_record()
connection()
listselect = lvroutine.SelectedItems.Item(0).Text
sql = "SELECT * From tblprogram WHERE MUSCLEGROUP ='" & listselect & "'"
cmd = New OleDbCommand(sql, con)
dr = cmd.ExecuteReader
If dr.Read Then
txtmuscle.Text = dr("MUSCLEGROUP")
editprogram.txtexname.Text = dr("EXERCISENAME")
editprogram.txteq.Text = dr("EQUIPMENT")
picpreview = dr("PREVIEW")
End If
End Sub
Private Sub clientprogram_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call get_data()
Call connection()
sql = "Select * From tblprogram ORDER BY MUSCLEGROUP ASC"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "tblprogram")
con.Close()
End Sub
Private Sub lvroutine_Click(sender As Object, e As EventArgs) Handles lvroutine.Click
txtmuscle.Text = lvroutine.SelectedItems(0).SubItems(0).Text
txtexercise.Text = lvroutine.SelectedItems(0).SubItems(1).Text
txtequipment.Text = lvroutine.SelectedItems(0).SubItems(2).Text
'picpreview.Image = Image.FromFile(lvroutine.SelectedItems(0).SubItems(3).ToString)<--- This is where the error is.
End Sub
End Class
First, make sure your path is the right path. Sometimes die Visual Studio throws this up. Just set a Breakpoint or open a MsgBox before executing the line of code (the line where the error appears) and take a look at it.
Secondly, you can try to load in in an Bitmap:
picpreview.Image = Bitmap.FromFile(lvroutine.SelectedItems(0).SubItems(3).ToString)
Also, i'm not 100% sure but isn't .ToString a methode? I came from the C# world but i'm think you have to add braces after .ToString:
picpreview.Image = Bitmap.FromFile(lvroutine.SelectedItems(0).SubItems(3).ToString**()**)
Give it a try and let me hear whats worked or, if so, did not worked.
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");