how do I refresh gridview after adding new row? - vb.net

I made several research but cannot figure out the problem. I can add, remove or edit rows from database in the code. However, I could not refresh the grid.
I mean, when I add new row to gridview, it doesn't appear in it. After I recompile the code it appears. How can I refresh the gridview?
Dim strSQL = "SELECT * FROM FIXEDCARD WHERE STKCODE = '" & TextEdit1.Text & "'"
objCon.Close()
Dim sqlCmd As New SqlCommand(strSQL, objCon)
objCon.Open()
Dim dreader As SqlDataReader
dreader = sqlCmd.ExecuteReader
If dreader.Read Then
'Dim stk_ As String = dreader.GetString(dreader.GetOrdinal("STKCODE")).ToString()
DevExpress.XtraEditors.XtraMessageBox.Show("already exists", "Info!", MessageBoxButtons.OK)
objCon.Close()
Else
dreader.Close()
strSQL = "INSERT INTO FIXEDCARD(STKCODE, STKEXP, AUTHCODE, GRPCODE, SPECODE" & _
", SPECODE2, SPECODE3, SPECODE4, SPECODE5, AMORTRATIO, AMORT," & _
"PURCH, SALES, RETUR, UNIT) VALUES('" & TextEdit1.Text & "'," & _
"'" & TextEdit2.Text & "', '" & TextEdit3.Text & "'," & _
"'" & TextEdit4.Text & "', '" & TextEdit5.Text & "'," & _
"'" & TextEdit6.Text & "', '" & TextEdit7.Text & "'," & _
"'" & TextEdit8.Text & "', '" & TextEdit9.Text & "'," & _
"'" & TextEdit10.Text & "', '" & TextEdit11.Text & "'," & _
"'" & TextEdit12.Text & "', '" & TextEdit13.Text & "'," & _
"'" & TextEdit14.Text & "', '" & TextEdit15.Text & "') "
sqlCmd = New SqlCommand(strSQL, objCon)
sqlCmd.ExecuteNonQuery()
objCon.Close()
End If
RefreshGrid()
Me.Close()
And also I try to write a refresh function that will refresh the gridview when I call it each button. However, I have been making a mistake but could not recognize it.
Public Sub RefreshGrid()
Dim T As New DataTable
Dim strSQL = "Select * From FIXEDCARD"
Dim sqlCmd As New SqlCommand(strSQL, objCon)
T = CType(sqlCmd.ExecuteNonQuery(), System.Data.DataTable)
GridView1.DataSource = T
End Sub

Public Function FillDataSet(query As String, ByVal ParamArray para() As Object) As DataTable
dim _transaction As SqlTransaction
Dim _command As SqlCommand
_command = New SqlCommand(query, yourConnection)
_ds = New DataSet
_sqlda = New SqlDataAdapter(_command )
_command.Transaction = _transaction
For i = 0 To para.Count - 1
_command.Parameters.AddWithValue("#" & i, para(i))
Next
_sqlda.Fill(_ds)
return _ds.tables(0)
End Function
call it
GridControl1.datasource = Nothing
GridControl1.datasource = FillDataSet(YourInsertQuery,YourParam)
GridControl1.RefreshDataSource()

You are using a "Non-Query" in the refresh. This doesn't return a table value.
Try using the SqlCommand.ExecuteReader method.
Reference: https://msdn.microsoft.com/en-us/library/9kcbe65k(v=vs.110).aspx

Related

Am trying to update data on vb.net with access database but the data does not update and there is no error

I have declared sql, cmd and cnt on public class, and also i have declare my database on Module.
Dim sql As String
Dim cmd As OleDb.OleDbCommand
Dim cnt As Long
Try
sql = "UPDATE [LDF] SET [Group_Code] = '" & ComboBox1.Text & "',
[Loan_Disb] ='" & TextBox1.Text & "',
[No_Of_Instalment] = '" & ComboBox2.Text & "',
[Single_Instalment]='" & TextBox2.Text & "',
[Loan_Security]='" & TextBox3.Text & "',
[Total_Amnt_TR]='" & TextBox4.Text & "',
[Member_Name]='" & TextBox5.Text & "',
[Group_Name]='" & TextBox6.Text & "',
[Date_Of_Disb]='" & DateTimePicker1.Value & "'
WHERE [Member_Number] = ' & ComboBox3.Text & '"
cmd = New OleDb.OleDbCommand(sql, Con)
cnt = cmd.ExecuteNonQuery
MsgBox("RECORD HAVE SUCCESSFUL UPDATED")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try

syntax error insert into statement vb.net

pls help solve me this question.. im very new to this
i can't add new employee to the table employee.. whenever i try to add it shows syntax error insert into statement
Public Class AddNewEmployee
Dim dr As OleDbDataReader
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim conn As New OleDbConnection(My.Settings.rayshadatabaseConnectionString)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn.Open()
Try
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
cmd = New OleDbCommand(str, conn)
Dim i As Integer = cmd.ExecuteNonQuery()
If i > 0 Then
MessageBox.Show("Record Succesfully added.", "Process Completed", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Adding failed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Close()
cmd.Dispose()
End Try
frmEmployee.loadR()
Me.Close()
End Sub
End Class
Replace this,
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
with this,
Dim str As String = "INSERT INTO employee" _
& "([Employee Name], [IC Number], [HP Number], [Address])" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
Thanks
Manoj

Inserting the current datetime in vb.net(DateTime to String Conversion)

I'm suppose to enter datatime to the database by passing this query
Dim regDate As DateTime = DateTime.Now
Dim strDate As String = regDate.ToString("yyyyMMddHHmmss")
I pass the "strDate" to the query,data type of my database table is datetime
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & regDate & "')")"
but it's getting error saying that
conversion failed when converting date and/or time from character string.
Help me to solve this problem
Dim regDate As DateTime = DateTime.Now
Dim strDate As String = regDate.ToString("yyyy-MM-dd HH:mm:ss")
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & strDate & "')")"
you have to pass strDate in query.Always use paremeterized query to avoid SQL injection
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & strDate & "')")"
May this works for you, at least it works for me on an acces db
Try
Dim cn As New OleDbConnection("your conection string here")
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
Dim sSQL As String = "insert into UserInfo(Date) values(#d1)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, cn)
Dim date As OleDbParameter = New OleDbParameter("#d1", OleDbType.Date, 15)
date.Value = DateTimePicker1.Text.ToString()
cmd.Parameters.Add(date)
If cmd.ExecuteNonQuery() Then
cn.Close()
MsgBox("successfully... ", MsgBoxStyle.Information, "Record Saved")
Else
MsgBox("failed... ", MsgBoxStyle.Critical, "Registration failed")
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Data Error")
Exit Sub
End Try
i hope this helps you,
regards Tom

vb.net Syntax error in INSERT INTO Statement with access

I'm getting an error during my insert can someone take a look?
Table:
VB.NET
Dim Name As String = txtName.Text
Dim JoinDate As String = dpJoinDate.Value
Dim DOB As String = dpDOB.Value
Dim ParentsName As String = txtParentsName.Text
Dim School As String = txtSchool.Text
Dim STD As String = txtSTD.Text
Dim Address As String = txtAddress.Text
Dim EMail As String = txtEMail.Text
Dim Mobile1 As String = txtMobile1.Text
Dim Mobile2 As String = txtMobile2.Text
Dim DurationStart As Date = dpDurationStart.Value
Dim DurationEND As Date = dpDurationEND.Value
Dim Fees As Decimal = Decimal.Parse(0.0)
Dim MaterialFees As Decimal = Decimal.Parse(0.0)
Dim LateFees As Decimal = Decimal.Parse(0.0)
Dim NextRenewal As Date = dpNextRenewal.Value
Dim Centre As String = cbCentre.Text
Dim Coach As String = cbCoach.Text
Dim picture As String = lblFileName.Text
Try
Fees = Decimal.Parse(txtFees.Text)
Catch
End Try
Try
MaterialFees = Decimal.Parse(txtMaterialFees.Text)
Catch
End Try
Try
LateFees = Decimal.Parse(txtLateFees.Text)
Catch
End Try
Dim Cmd As OleDbCommand
Dim SQL As String
Dim objCmd As New OleDbCommand
Dim Con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=./AcademyDatabase.accdb;Persist Security Info=False;")
SQL = "INSERT INTO Student (FullName,JoinDate,DOB,ParentsName,School,STD,Address,EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees,MaterialFees,LateFees,NextRenewal,Centre,Coach,Image,DropOut) VALUES ('" _
& Name & "','" _
& JoinDate & "','" _
& DOB & "','" _
& ParentsName & "','" _
& School & "','" _
& STD & "','" _
& Address & "','" _
& EMail & "','" _
& Mobile1 & "','" _
& Mobile2 & "','" _
& DurationStart & "','" _
& DurationEND & "','" _
& Fees & "','" _
& MaterialFees & "','" _
& LateFees & "','" _
& NextRenewal & "','" _
& Centre & "','" _
& Coach & "','" _
& picture & "'," _
& "0)"
Cmd = New OleDbCommand(SQL, Con)
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
Dim rowCount As Integer = 0
Try
rowCount = objCmd.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Sql:
"INSERT INTO Student (FullName,JoinDate,DOB,ParentsName,School,STD,Address,EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees,MaterialFees,LateFees,NextRenewal,Centre,Coach,Image,DropOut) VALUES ('','3/13/2014','1/1/1900','','fadsasdffdas','','','','','','1/1/1900','1/1/1900','0','0','0','1/1/1900','','','',0)"
IMAGE is a reserved keyword. If you want to use it for a column name, then your need to encapsulate it with square brackets
"INSERT INTO Student " & _
"(FullName,JoinDate,DOB,ParentsName,School,STD,Address," & _
"EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees," & _
"MaterialFees,LateFees,NextRenewal,Centre,Coach,[Image],DropOut) VALUES ...."
If you are still able to do so, I suggest to change the name of that column to a NON reserved keyword, otherwise you will alway have this problem when you try to use that column.
Said that, please, read about parameterized queries. Your code has a big problem and it is called SQL Injection (not to mention the parsing problems for strings, date and decimals)
SQL = "INSERT INTO Student " & _
"(FullName,JoinDate,DOB,ParentsName,School,STD,Address," & _
"EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees," & _
"MaterialFees,LateFees,NextRenewal,Centre,Coach,[Image],DropOut) " & _
"?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0)"
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
objCmd.Parameters.AddWithValue("#p1", Name)
objCmd.Parameters.AddWithValue("#p2", JoinDate)
.... add the other missing parameters with their values.....
objCmd.Parameters.AddWithValue("#p18", picture)
Dim rowCount As Integer = 0
rowCount = objCmd.ExecuteNonQuery()

how to refresh datagrid and update database?

i have some trobles in updating my database. ihave this codes :
Dim cmd As OleDbCommand
Dim sql As String
sql = "UPDATE nmat SET nip = '" & lblNipDosen.Text & "', nim = '" & TxtNIM.Text & "', ntugas = '" & TxtNtugas.Text & "', nabsensi = '" & TxtNabsen.Text & "', nuts = '" & TxtNuts.Text & "', nuas = '" & TxtNuas.Text & "' WHERE nim='" & TxtNIM.Text & "'"
conn.Open()
Dim reader As OleDbDataReader
Try
cmd = New OleDbCommand(sql, conn)
cmd.ExecuteNonQuery()
DataGridView1.Refresh()
Finally
'reader.Close()
End Try
conn.Close()
my problem is, by these code, the grid can be refreshed after i close and open this form again. but if i check in my ms Access, the data was not chanded at all. how to update my database and showed in my datagrid??
Try This :
Dim cmd As OleDbCommand
Dim rstTable As New DataTable()
Dim sql As String
sql = "UPDATE nmat SET nip = '" & lblNipDosen.Text & "', nim = '" & TxtNIM.Text & "', ntugas = '" & TxtNtugas.Text & "', nabsensi = '" & TxtNabsen.Text & "', nuts = '" & TxtNuts.Text & "', nuas = '" & TxtNuas.Text & "' WHERE nim='" & TxtNIM.Text & "'"
conn.Open()
Dim reader As OleDbDataReader
Try
cmd = New OleDbCommand(sql, conn)
rstTable.Load(cmd.ExecuteReader())
DataGridView1.DataSource =rstTable
Finally
'reader.Close()
End Try
conn.Close()
your gridview columns should have bound to a field