Related
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
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
I am Trying to create New access table in a database but when i try to name it from text box it is giving an error
Sub CreateTable()
Dim strCreate As String = "CREATE TABLE" & TxtBoxTblName.Text &(" & _
"CountryName varchar(120) Primary key," & _
"Continent Integer," & _
"Area Long," & _
"Population Long," & _
"Capital varchar(80)," & _
"Code char(2));"
Dim conDatabase As OleDbConnection = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" & _
"Data Source=""Data Source=" & filename & ".mdb;")
Dim cmdDatabase As OleDbCommand = New OleDbCommand(strCreate, conDatabase)
conDatabase.Open()
cmdDatabase.ExecuteNonQuery()
conDatabase.Close()
MessageBox.Show("Table Created Sucessfully")
End Sub
I guess you missed a " in this line "CREATE TABLE" & TxtBoxTblName.Text &(" & _ and these in no space after CREATE TABLE keyword that will also yields error. so it should be "CREATE TABLE " & TxtBoxTblName.Text &"(" & _ See the difference here or try below code
Dim STR_DDL As String
STR_DDL = "CREATE TABLE #TABLENAME# (CountryName varchar(120) Primary key,Continent Integer,Area Long,Population Long,Capital varchar(80),Code char(2));"
STR_DDL.Replace("#TABLENAME#", Trim(TxtBoxTblName.Text))
OR
using Composite Formatting
Dim STR_DDL As String = String.Format("CREATE TABLE {0} (CountryName varchar(120) Primary key " & _
",Continent Integer,Area Long,Population Long,Capital varchar(80) " & _
",Code char(2));", Trim(TxtBoxTblName.Text))
{0} is a place holder for TxtBoxTblName.Text
and use it
Dim cmdDatabase As OleDbCommand = New OleDbCommand(STR_DDL , conDatabase)
I'm having trouble creating Access tables from VB.NET.
This is the code I have come up with but I keep getting errors:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
'connection string
Dim dbpath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
dbpath = New Uri(dbpath).LocalPath
Dim my_connection As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\GhostDrive\Desktop\database.mdb"
Dim userTables As DataTable = Nothing
Dim connection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection()
Dim source As String
'query string
Dim my_query As String = "CREATE TABLE " & TextBox2.Text & " ( " & _
"ID Counter, " & _
"Year datetime," & _
"Title varchar(40)," & _
"image1 Long," & _
"Image2 Long," & _
"Image3 Long," & _
"Image4 Long," & _
"Serial varchar(20)," & _
"Purchaseprice Currency," & _
"Evalprice Currency, " & _
"Datepurchase DateTime, " & _
"Dateeval DateTime, " & _
"Sign varchar(40), " & _
"Grading varchar(20)," & _
"Eval YesNo, " & _
"Star YesNo, " & _
"Folder YesNo, " & _
"Forsale YesNo, " & _
"Error YesNo, " & _
"Barcode(varchar(20)," & _
"Comm YesNo )"
'create a connection
Dim my_dbConnection As New OleDbConnection(my_connection)
'create a command
Dim my_Command As New OleDbCommand(my_query, my_dbConnection)
'connection open
my_dbConnection.Open()
'command execute
my_Command.ExecuteNonQuery()
'close connection
my_dbConnection.Close()
ListBox1.Items.Clear()
source = TextBox1.Text
connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + source
Dim restrictions() As String = New String(3) {}
restrictions(3) = "Table"
connection.Open()
' Get list of user tables
userTables = connection.GetSchema("Tables", restrictions)
connection.Close()
' Add list of table names to listBox
Dim i As Integer
For i = 0 To userTables.Rows.Count - 1 Step i + 1
ListBox1.Items.Add(userTables.Rows(i)(2).ToString())
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
if i take all them out except ID it works and then i add them on by on back it stops "Year datetime," & _
YEAR is a reserved word in Access SQL. If I try to run the following code ...
Dim connectionString As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Users\Public\mdbTest.mdb;"
Using con As New OleDbConnection(connectionString)
con.Open()
Using cmd As New OleDbCommand()
cmd.Connection = con
cmd.CommandText = "CREATE TABLE zzzTest (ID COUNTER, Year INTEGER)"
Try
cmd.ExecuteNonQuery()
Console.WriteLine("Table created.")
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
con.Close()
End Using
... I get
Syntax error in field definition.
However, if I enclose the field name in square brackets ...
cmd.CommandText = "CREATE TABLE zzzTest (ID COUNTER, [Year] INTEGER)"
... then I get
Table created.
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()