ListView in VB.NET (VS 2010) - sql

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

Related

Get Image from SQL using Listbox to picturebox VB

i'm trying to get the image from SQL to picturebox using Listbox in in VB.
here is my sql sample table.
and here is my VB Design form, so what I'm trying to do is when I load the form, if an item in the listbox is selected, i want it to get the image(Binary Data) from sql to picturebox in vb net.
and the code I'm working with it give me this error:
VB full code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connect()
Dim co As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True")
co.Open()
Dim com As New SqlCommand("SELECT Image from Items where ItemName = '" & ListBox1.SelectedIndex & "'", co)
Dim img As Byte() = DirectCast(com.ExecuteScalar(), Byte())
Dim ms As MemoryStream = New MemoryStream(img)
Dim dt = GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = dt
ListBox1.DisplayMember = "ItemName"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "ItemID")
TextBox2.DataBindings.Add("Text", BndSrc, "ItemName")
TextBox3.DataBindings.Add("Text", BndSrc, "Details")
PictureBox1.Image = Image.FromStream(ms)
End Sub
Private Function GetDataFromSql() As DataTable
Dim dt As New DataTable
Using connection As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True"),
cmd As New SqlCommand("select * FROM Items", connection)
connection.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Remove the picture retrieval from the Form.Load. We have selected all the data in the GetDataFromSql function. The magic happens in the ListBox1.SelectedIndexChanged method.
The SelectedIndexChanged will occur as a result of the code in the Form.Load and every time the selection changes. When we bind the the list box to to binding source the entire row is added as a DataRowView. We can use this to get the data in the Image column. First check if the field is null. Next cast to a byte array. Take the byte array and pass it to the constructor of a MemoryStream. Streams need to be disposed so it is in a Using block. Finally the stream can be assigned to the Image property of the PictureBox.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = dt
ListBox1.DisplayMember = "ItemName"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "ItemID")
TextBox2.DataBindings.Add("Text", BndSrc, "ItemName")
TextBox3.DataBindings.Add("Text", BndSrc, "Details")
End Sub
Private Function GetDataFromSql() As DataTable
Dim dt As New DataTable
Using connection As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True"),
cmd As New SqlCommand("select * FROM Items", connection)
connection.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim row = DirectCast(ListBox1.SelectedItem, DataRowView)
If row("Image") IsNot Nothing Then
Dim b() As Byte = DirectCast(row("Image"), Byte()) '< ------ Cast the field to a Byte array.
Using ms As New System.IO.MemoryStream(b)
PictureBox1.Image = System.Drawing.Image.FromStream(ms)
End Using
Else
PictureBox1.Image = Nothing
End If
End Sub
EDIT
I switched the code over to a database I have available for testing. Even though it is not your database, I am sure you will be able to follow the code.
Here is the schema of my database.
The main difference is I moved the DataTable to a class level variable so it can be seen from all methods. I changed the GetDataFromSql to a Sub. It adds the data to the class level DataTable (Bounddt). The AddItem method first gets the Byte() from a file. The row is added to the DataTable with an Object array with elements that match the DataTable.
Private Bounddt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = Bounddt
ListBox1.DisplayMember = "CustomerID"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "CustomerID")
TextBox2.DataBindings.Add("Text", BndSrc, "CustomerName")
End Sub
Private Sub GetDataFromSql()
Using connection As New SqlConnection("Data Source=****;Initial Catalog='Small Database';Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"),
cmd As New SqlCommand("select * FROM Sales.Customer", connection)
connection.Open()
Using reader = cmd.ExecuteReader
Bounddt.Load(reader)
End Using
End Using
'Return dt
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim row = DirectCast(ListBox1.SelectedItem, DataRowView)
If row("Picture") IsNot Nothing Then
Dim b() As Byte = DirectCast(row("Picture"), Byte()) '< ------ Cast the field to a Byte array.
Using ms As New System.IO.MemoryStream(b)
PictureBox1.Image = System.Drawing.Image.FromStream(ms)
End Using
Else
PictureBox1.Image = Nothing
End If
End Sub
Private Sub AddItem()
Dim picture = GetByteArr("C:\Users\maryo\OneDrive\Documents\Graphics\Animals\squirrel.png")
Bounddt.Rows.Add({5, "George", 74, 62, "George", picture})
End Sub
Private Function GetByteArr(path As String) As Byte()
Dim img = Image.FromFile(path)
Dim arr As Byte()
Dim imgFor As Imaging.ImageFormat
Dim extension = path.Substring(path.LastIndexOf(".") + 1)
'There is a longer list of formats available in ImageFormat
Select Case extension
Case "png"
imgFor = Imaging.ImageFormat.Png
Case "jpg", "jpeg"
imgFor = Imaging.ImageFormat.Jpeg
Case "bmp"
imgFor = Imaging.ImageFormat.Bmp
Case Else
MessageBox.Show("Not a valid image format")
Return Nothing
End Select
Using ms As New MemoryStream
img.Save(ms, imgFor)
arr = ms.ToArray
End Using
Return arr
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddItem()
End Sub
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Dim con As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader
Dim da As SqlDataAdapter
Private Const cs As String = "ConnectionString"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SqlConnection(cs)
con.Open()
cmd = New SqlCommand("select * from [dbo].[Item_Details]", con)
rdr = cmd.ExecuteReader()
While rdr.Read
ListBox1.Items.Add(rdr(1))
End While
con.Close()
End Sub
Private Sub ListBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseClick
Try
con = New SqlConnection(cs)
con.Open()
da = New SqlDataAdapter("Select * from Item_Details where itemname='" & ListBox1.SelectedItem.ToString() & "'", con)
Dim dt As New DataTable
da.Fill(dt)
For Each row As DataRow In dt.Rows
TextBox1.Text = row(0).ToString()
TextBox2.Text = row(1).ToString()
TextBox3.Text = row(2).ToString()
Dim data As Byte() = row(3)
Dim ms As New MemoryStream(data)
PictureBox1.Image = Image.FromStream(ms)
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class

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

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

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

update database from data grid view in vb.net

i have a data grid view, filled by data from database now i need to change the data and update database.
Private daVD As New OracleDataAdapter
Private cmdJV As New OracleCommandBuilder
Private dtVD As New DataTable()
Dim cmd As New OracleCommand("Select JV_CODE,JV_ACC_NAME,DEBIT,CREDIT From VOUCHER_DETAIL where VOUCHERNO =:Vno", sgcnn)
cmd.Parameters.Add("#Vno", OracleDbType.NVarchar2).Value = txtJVNo.Text.ToString.Trim
dtVD.Clear()
daVD = New OracleDataAdapter(cmd)
daVD.Fill(dtVD)
dgvAccDetail.AutoGenerateColumns = False
dgvAccDetail.DataSource = dtVD
If dtVD.Rows.Count > 0 Then
For i As Integer = 0 To dtVD.Rows.Count - 1
''Dim DataType() As String = myTableData.Rows(i).Item(1)
dgvAccDetail.Rows(i).Cells(0).Value = dtVD.Rows(i).Item("JV_CODE").ToString.Trim
dgvAccDetail.Rows(i).Cells(1).Value = dtVD.Rows(i).Item("JV_ACC_NAME").ToString.Trim
dgvAccDetail.Rows(i).Cells(2).Value = dtVD.Rows(i).Item("DEBIT").ToString.Trim
dgvAccDetail.Rows(i).Cells(3).Value = dtVD.Rows(i).Item("CREDIT").ToString.Trim
Next
End If
i tried many different ways to update the database table but not working
Try
cmdJV = New OracleCommandBuilder(da)
daJV.Update(ds, "VJ_Details")
ds.AcceptChanges()
MessageBox.Show(" The record has been updated.")
Catch ex As Exception
MsgBox(ex.Message)
End Try
I have never used Oracle, but this is how you could do it using SQL Server (there are actually several ways to push data from a DatGridView to a table in SQL Server).
Here is one option for you to try.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=Server_Name\SQLEXPRESS;Initial Catalog=Test;Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Orders"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub DataGridView1_Click(sender As Object, e As EventArgs) Handles DataGridView1.Click
DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Orange
End Sub
End Class
Here is one more option for you to consider.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Server_Name\SQLEXPRESS;Database=Database_Name;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub

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");