Save and Update from Datagridview to Access Database - vb.net

i've been fumbling with this problem for a while now. am trying to update/insert into my access database data from a datagridview on a form.
i've a maskedtextbox that i've masked to suit my primary key. when the mask is completed then automatically, records are read from the database to the textboxes and datagridview as shown in the attached picture.
i did that with this code
If STHN_ID.MaskCompleted = True Then
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
'da = New OleDbDataAdapter("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn) 'Change items to your database name
'da.Fill(ds)
'Dim view As New DataView(tables(0))
'source1.DataSource = view
'DependantView.DataSource = view
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
'connection.Open()
Dim myTable As DataTable = New DataTable
adapter.Fill(myTable)
DependantView.DataSource = myTable
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
my headache now is to update/insert into the database when records are added/edited in the datagridview based on the STHN_ID entered in the maskedtextbox. any help would be really appreciated.
sample

this is how i got it done!
on maskedtextbox with mask completed this is the code to read from database and load datagridview ...........
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
con = New OleDbConnection
con.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\PRINCE\Documents\STHNDatabase.accdb")
con.Open()
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
Dim connection As New OleDbConnection
connection.ConnectionString = connString
adapt = New OleDbDataAdapter("Select [DependentID],[DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship],[STHN_ID] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", con)
ds = New DataSet
adapt.Fill(ds, "DependantData")
DependantView.DataSource = ds.Tables(0)
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
and on the SaveButton Click this is the code.....
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
Try
builder = New OleDbCommandBuilder(adapt)
adapt.Update(ds, "DependantData")
MsgBox("Updated Successfully")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
thanks once again. really appreciate it

Related

How to add dynamic Data in to the datagridviewcombobox column?

I am Developing VB.net application.
In that application I take DataGirdView to display data.
I took DataSource property of the datagridview to display 3 columns' data directly from database.
After those columns I add another DataGridViewComboBoxColumn. Then I a want to add dynamic the data into that ComboBoxColumn.
how to do this?
Private Function CreatComboBoxWithEnum() As DataGridViewComboBoxColumn
Dim combo As New DataGridViewComboBoxColumn()
Sqlconn = New SqlConnection
Sqlconn.ConnectionString = "server=.\SQLEXPRESS_2005;Initial Catalog=MachineShopScheduling ;Integrated Security=SSPI;"
Dim adpter As New SqlDataAdapter
Dim ds As New DataTable
Try
Sqlconn.Open()
Dim Query As String
For Each dr As DataGridViewRow In DataGridView1.Rows
Dim val As String = dr.Cells("SrDataGridViewTextBoxColumn").Value.ToString
Query = "select OperationNo from RoutingCalculation where Sr ='" & val & "' "
COMMAND = New SqlCommand(Query, Sqlconn)
adpter.SelectCommand = COMMAND
adpter.Fill(ds)
combo.DataSource = ds
combo.DataPropertyName = "OperationNo"
combo.Name = "OperationNo"
OperationNo.ValueMember = "OperationNo"
OperationNo.DisplayMember = "OperationNo"
Next
Sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return combo
End Function
Private Sub load_operationNo()
Sqlconn = New SqlConnection
Sqlconn.ConnectionString = "server=.\SQLEXPRESS_2005;Initial Catalog=MachineShopScheduling ;Integrated Security=SSPI;"
Try
op.Name = "OperationNo"
DataGridView1.Columns.Add(op)
Sqlconn.Open()
Dim Query As String
Dim i As Integer = 0
For Each dr As DataGridViewRow In DataGridView1.Rows
Dim OPno As New DataGridViewComboBoxCell
With OPno
Dim adpter As New SqlDataAdapter
Dim dt As New DataTable
Dim val As String = dr.Cells("SrDataGridViewTextBoxColumn").Value.ToString
Query = "select OperationNo from RoutingCalculation where Sr = " & val & " order by sr"
Using cmd As New SqlCommand(Query, Sqlconn)
adpter.SelectCommand = cmd
adpter.Fill(dt)
End Using
.DataSource = dt
.ValueMember = "OperationNo"
.DisplayMember = "OperationNo"
DataGridView1.Rows(i).Cells("OperationNo") = OPno
i = i + 1
End With
Next
Sqlconn.Close()
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
End Sub
This is the code to add dynamically add the data into DatagridViewComboboxColumn

DataReader Error VB.net and mySql

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim reader As MySqlDataReader
Dim query As String
Dim md As String
md = Me.mskmembdate.Text
md = Me.bday.Text
md = Me.spsbday.Text
Try
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
query = "SELECT * FROM member WHERE (memor = '" & membor.Text & "')"
sqlcom = New MySqlCommand(query, conn)
reader = sqlcom.ExecuteReader
While reader.Read()
Me.lblmembname.Text = reader("membname").ToString
Me.membtype.Text = reader("membtype").ToString
Me.mskmembdate.Text = CDate(reader("membdate")).ToString("MMddyyyy")
Me.lname.Text = reader("lname").ToString
Me.fname.Text = reader("fname").ToString
Me.mname.Text = reader("mname").ToString
Me.nameex.Text = reader("nameex").ToString
Me.bday.Text = CDate(reader("bday")).ToString("MMddyyyy")
Me.membtype.Text = reader("membtype").ToString
Me.spslname.Text = reader("spslname").ToString
Me.spsfname.Text = reader("spsfname").ToString
Me.spsmname.Text = reader("spsmname").ToString
Me.spsbday.Text = CDate(reader("spsbday")).ToString("MMddyyyy")
Me.civil.Text = reader("civil").ToString
Me.sex.Text = reader("sex").ToString
Me.municipal.Text = reader("municipal").ToString
Me.brgy.Text = reader("brgy").ToString
Me.purok.Text = reader("purok").ToString
Me.district.Text = reader("district").ToString
Me.certno.Text = reader("certnumb").ToString
Me.resno.Text = reader("resonumb").ToString
Me.cpno.Text = reader("cpno").ToString
Me.recstat.Text = reader("recstat").ToString
End While
reader.Close()
conn.Dispose()
Catch ex As Exception
End Try
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim dr As OleDbDataReader
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "D:\N.A.C. JR\SAMPLE VB 2008\NewMembership\NewMembership\bin\Debug\profilepic.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM info WHERE (memor = '" & membor.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader()
While dr.Read()
orspspic.Text = dr("spspicture").ToString
orpic.Text = dr("picture").ToString
End While
dr.Close()
myConnection.Close()
varimage = orpic.Text
varimage = orspspic.Text
pic.ImageLocation = orpic.Text
spspic.ImageLocation = orspspic.Text
End Sub
This is my code from frmload i click listview data then form2 opens and sets the data into text boxes but this error pops out "There is already an open DataReader associated with this Connection which must be closed first" ? How can i solve it . Any ideas how to solve this kind of problem?

Trouble loading data into textbox

Upon the click of a button, I want the program to load in details about the user (stored in an access database) into the textboxes.
This is what I have to far
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Documents\RailwayDatabase2.accdb"
Dim MyConn As New OleDbConnection(connString)
Dim da As OleDbDataAdapter
Dim ds As DataSet
Try
MyConn.Open()
da = New OleDbDataAdapter("Select * from tbl_employees WHERE FirstName = """ & EmployeeLogin.usersname & """", MyConn)
ds = New DataSet
da.Fill(ds)
TextBox1.Text = ds.Tables("tbl_employees").Rows(0).Item(2)
MyConn.Close()
Catch ex As Exception
If MyConn.State <> ConnectionState.Closed Then MyConn.Close()
End Try
End Sub
any idea why this isn't working? thanks

how to display database into combobox

im getting error in combobox, instead the combobox display the database... it shows combobox.text = "System.Data.DataRowView" inside.
Private Sub FillCombo()
Try
conn = New OleDbConnection(Get_Constring)
Dim sSQL As String = ("SELECT subject FROM student order by subject")
Dim da As New OleDbDataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds)
cmbsection.ValueMember = "ItemName"
cmbsection.DataSource = ds.Tables(0)
cmbsection.SelectedIndex = 0
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub
I think this is a simple case of setting the Datasource before the Valuemember.
cmbsection.DataSource = ds.Tables(0)
cmbsection.ValueMember = "ItemName"
Try this
Private Sub FillCombo()
Try
conn = New OleDbConnection(Get_Constring)
Dim sSQL As String = ("SELECT subject FROM student order by subject")
Dim da As New OleDbDataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds)
cmbsection.ValueMember = "ItemName"
cmbsection.DataSource = ds;
cmbsection.SelectedIndex = 0;
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
You need to set the
cmbsection.DisplayMember = "Subject"
cmbsection.ValueMember = "Subject"
Private Sub FillCombo()
Try
conn = New OleDbConnection(Get_Constring)
Dim sSQL As String = ("SELECT subject FROM student order by subject")
Dim da As New OleDbDataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds)
cmbsection.Items.clear
For i as Integer = 0 to ds.Tables(0).rows.count-1
cmbsection.Items.add( ds.Tables(0).rows(i).item("subject").tostring)
next
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub
Public Sub LoadProvince()
Dim cn As New SqlConnection("server=.\LENOVO;uid=sa;pwd=123;database=SchoolDb;")
cn.Open()
Dim cmd As New SqlCommand("SELECT * FROM Product;", cn)
Dim dr = cmd.ExecuteReader()
Dim dt As New DataTable()
dt.Load(dr)
dr.Close()
cboPROVINCE.DisplayMember = "Product_NAME"
cboPROVINCE.ValueMember = "Product_Id"
cboPROVINCE.DataSource = dt
End Sub

error :ExecuteNonQuery: CommandText property has not been initialized

this code is in the button click , i get each data out using spilt
but i encounter error at "cmd.CommandType = CommandType.Text"
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
the same code , the below work
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO GuestList (groupID,guest,contact,eEmail,relationship,info,customerID) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}'); ", sqlStatement, splitItems(0), splitItems(1), splitItems(2), splitItems(3), splitItems(4), splitItems(5), Session("customerID"))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
You never set the CommandText property.
You don't need to set CommandType at all.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
dim dt as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblGender )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox1
.DataSource = dt
.DisplayMember = "Gender"
End With
dim dt1 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblStatus )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox2
.DataSource = dt1
.DisplayMember = "Status"
End With
dim dt2 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblDepartment )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox3
.DataSource = dt2
.DisplayMember = "Department"
End With
End Sub
See this
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
'Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
'If item.Contains(",") Then
' splitItems = item.Split(",".ToCharArray())
' sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
'End If
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}({1},'{2}'); ", sqlStatement, splitItems(0), splitItems(1))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try