how to add data in sql database with datagridview - sql

heres my code in adding data to sql database
Dim ConStr As String = "Data Source=SYSTEMS-LAPTOP\DEVSQL;Initial Catalog=ContactDB;Persist Security Info=True;User ID=sa;Password=P#ssw0rd123"
Dim sql As String = "SELECT * FROM dataContactDB"
Dim sqlCon As New SqlConnection
Dim sqlCmd As New SqlCommand
Dim sqlAdapter As SqlDataAdapter
Dim sqlBuilder As SqlCommandBuilder
Dim sqlDataset As DataSet
Dim sqlTable As DataTable
this code loads my data in datagridview from sqldatabase
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
sqlCon = New SqlConnection(ConStr)
sqlCon.Open()
sqlCmd = New SqlCommand(sql, sqlCon)
sqlAdapter = New SqlDataAdapter(sqlCmd)
sqlBuilder = New SqlCommandBuilder(sqlAdapter)
sqlDataset = New DataSet
sqlAdapter.Fill(sqlDataset, "dataContactDB")
sqlTable = sqlDataset.Tables("dataContactDB")
sqlCon.Close()
dgData.DataSource = sqlDataset.Tables("dataContactDB")
dgData.ReadOnly = True
dgData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
my codes in adding data to sqldatabase
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
sqlCon.Open()
sqlCmd.CommandText = "insert into dataContactDB(con_Name,con_Phone,Address,Company,Gender) values('" & txtName.Text & "','" & txtPhone.Text & "','" & txtAddress.Text & "','" & txtCompany.Text & "','" & txtGender.Text & "')"
sqlCmd.ExecuteNonQuery()
sqlCon.Close()
End Sub
all i want to do is when you add data in sqldatabase. datagridview will retrieve the new added data and add it on its list. every time i add data . datagridview didnt show my recent added data, how do i do that?

You simply have to reload the data in grid. Put all code the in a function named LoadMyGrid, that you have written in frm_load. Now call this method from frm_load. Also call same method in your button click event in the last line.

Related

Retrieving data between two dates from Access database using VB.NET

I want to display data from a database in a datagridview. I am getting error on da.Fill(ds, "SAMPLE") with "data type mismatch error". Please see screenshot.
My date formats are 'short date' both datetimepicker and database values.
Imports System.Data.OleDb
Public Class Form1
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Recto D Sanchez Jr\Documents\sample.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from SAMPLE where [LOGDATE] between '" & DateTimePicker1.Text & "' And '" & DateTimePicker2.Text & "'", MyConn)
da.Fill(ds, "SAMPLE")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
End Sub
End Class
error screenshot
Since your DateTimePicker controls already deal with proper DateTime values you might have better luck using a parameterized query like this:
MyConn = New OleDbConnection(connString)
Dim cmd As New OleDbCommand("SELECT * FROM [SAMPLE] WHERE [LOGDATE] Between ? And ?", MyConn)
cmd.Parameters.AddWithValue("?", DateTimePicker1.Value.Date)
cmd.Parameters.AddWithValue("?", DateTimePicker2.Value.Date)
da = New OleDbDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "SAMPLE")
It would save you the trouble of dealing with different date formats, delimiting date literals, and other potential pitfalls.
Try
da = New OleDbDataAdapter("Select * from SAMPLE where [LOGDATE] between #" & DateTimePicker1.Value.ToString("MM/dd/yyyy HH:mm:ss") & "# And #" & DateTimePicker2.Value.ToString("MM/dd/yyyy HH:mm:ss") & "#", MyConn)

Oracle INSERT on VB.net Null reference exception

Please help i am a newbie on oracle database i am used on using mysql and i really don't have any idea how can i debug my code. Here is my code.
Imports System.Diagnostics
Imports Oracle.DataAccess.Client
Imports Oracle.DataAccess.Types
Public Class mainMenu
Dim conn As New OracleConnection
Private cmd As OracleCommand
Private da As OracleDataAdapter
Private cb As OracleCommandBuilder
Private ds As DataSet
Private Sub mainMenu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler txtProductName.TextChanged, AddressOf ValidateInputs
AddHandler txtQty.TextChanged, AddressOf ValidateInputs
AddHandler txtPrice.TextChanged, AddressOf ValidateInputs
conn.ConnectionString = "User Id=antonina" & _
";Password=antonina" & _
";Data Source=xe"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
Finally
conn.Dispose()
End Try
End Sub
Private Sub ValidateInputs(ByVal Sender As Object, ByVal e As EventArgs)
Button1.Enabled = Not (txtProductName.Text = String.Empty OrElse txtQty.Text = String.Empty OrElse txtPrice.Text = String.Empty)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim productName As String
Dim qty As Integer
Dim price As Integer
Dim cat As String
productName = txtProductName.Text
qty = Integer.Parse(txtQty.Text)
price = Integer.Parse(txtPrice.Text)
cat = cmbCat.Text
conn = New OracleConnection("User Id=antonina;Password=antonina;Data Source=xe")
da = New OracleDataAdapter()
Try
da.InsertCommand = New OracleCommand("INSERT INTO INVENTORY(INVENTORY_PRODUCTNAME,INVENTORY_CAT,INVENTORY_QTY,INVENTORY_PRICE) VALUES ('" & productName & "'," & qty & "," & price & ",'" & cat & "')", conn)
Debug.WriteLine("Success")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
When i click my add button it says object reference not set to an instance of an object. I know i might just have a stupid syntax error. Please help me.
I am sure that all my variables have a value. also i am using oracle 10g
I have never seen that somebody uses a OracleDataAdapter in order to insert anything to database, usually OracleDataAdapter is used to retrieve data from database, i.e. a SELECT ... command or a function call which gets a RefCursor.
Perhaps InsertCommand, resp. UpdateCommand and DeleteCommand are used to modify data of OracleDataAdapter after it has been filled from your database - I do not know, I never used it. These command are called with method OracleDataAdapter.Update(da)
Anyway, usually you would do it like this:
Dim cmd As OracleCommand
cmd = New OracleCommand("INSERT INTO INVENTORY (INVENTORY_PRODUCTNAME,INVENTORY_QTY,INVENTORY_PRICE,INVENTORY_CAT) VALUES (:productName, :qty, :price, :cat)", conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("productName", OracleDbType.Varchar2, ParameterDirection.Input).Value = productName
cmd.Parameters.Add("qty", OracleDbType.Int32, ParameterDirection.Input).Value = qty
cmd.Parameters.Add("price", OracleDbType.Int32, ParameterDirection.Input).Value = price
cmd.Parameters.Add("cat", OracleDbType.Varchar2, ParameterDirection.Input).Value = cat
cmd.ExecuteNonQuery()
Note the order of columns, see your code:
INVENTORY_PRODUCTNAME, INVENTORY_CAT, INVENTORY_QTY, INVENTORY_PRICE
('" & productName & "'," & qty & "," & price & ",'" & cat & "')"
I assume da is for DataAdapter. You need first instantiate your dataadapter by call its constructor.
conn = new OracleConnection(yourConnectionString)
da = New OracleDataAdapter()
da.InsertCommand = New OracleCommand("INSERT INTO INVENTORY(INVENTORY_PRODUCTNAME,INVENTORY_CAT,INVENTORY_QTY,INVENTORY_PRICE) VALUES ('" & productName & "'," & qty & "," & price & ",'" & cat & "')", conn)
also, you missing '()' after VALUES statement in sql syntax.
Other things may help is you can move your parsing statement into try-catch element to avoid error.
hope this help.

How to do a registerform by ASP.NET VB SQL

I am designing a registerform by vb.net but I don't know how to do this.
The following is my code:
Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim Conn As SqlConnection = New SqlConnection("localdb\v11.0")
Conn.Open()
Dim sqlstr As String = "insert into user_profile(username,password,nickname,realname,email) values('&username.Text&','&password.Text&','&nickname.Text&','&realname.Text&','&email.Text&')"
Dim cmd As New SqlCommand(sqlstr, Conn)
cmd.ExecuteNonQuery()
cmd.Cancel()
Conn.Close()
Conn.Dispose()
End Sub
but there is some errors...
and, is this concept right? If click the button then insert the data into SQL database?
Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim Conn As SqlConnection = New SqlConnection("localdb\v11.0")
Conn.Open()
Dim sqlstr As String = "insert into user_profile(username, password, nickname, realname, email) values('" & username.Text & "','" & password.Text & "','" & nickname.Text & "','" & realname.Text & "','" & email.Text &"')"
Dim cmd As New SqlCommand(sqlstr, Conn)
cmd.ExecuteNonQuery()
cmd.Cancel()
Conn.Close()
Conn.Dispose()
End Sub
You need to build your sqlstr correctly ... use quotes to separate the string from values of text boxes. You are also open to sql injections you should use paramaterised values.

How to get count of records in a table?

Someone help me
I am working on our project and I need to check if my DB has already 20 records.
If so, then it will not accept records anymore.
I've been trying the codes below:
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim ds, ds2 As New DataSet
Dim da, da2 As OleDb.OleDbDataAdapter
Dim sql, sql1 As String
Dim int As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.ConnectionString = "Provider=Microsoft.jet.OLEDB.4.0; data source = |datadirectory|\Database6.mdb"
con.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts WHERE Username='" & TextBox1.Text & "'", con)
Dim sdr As OleDb.OleDbDataReader = cmd.ExecuteReader
Dim cmd1 As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts")
sql = "INSERT INTO Accounts ([Username], [Password], [FirstName], [LastName]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "') "
sql1 = "SELECT Count([AccountID]) FROM Accounts"
cmd = New OleDb.OleDbCommand(sql, con)
cmd1 = New OleDb.OleDbCommand(sql1, con)
Convert.ToInt32(sql1)
cmd1.ExecuteScalar()
If sql1 < 20 Then
MsgBox("Cannot accept records")
ElseIf sdr.HasRows = False Then
cmd.ExecuteNonQuery()
MsgBox("Account Added")
ElseIf sdr.HasRows = True Then
MsgBox("Username is taken")
End If
con.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Hide()
Form2.Show()
End Sub
End Class
But the convert code fires an error :
Input string was in incorrect format
But if I delete the convert code it gives me the error
Conversion from string "SELECT Count([AccountID]) FROM A" to type 'Double' is not valid."
Help me please.
TIA
I dont know VB all that well, this is from the top of my head. Your trying to convert your SQL text, which will never work. Try something like this:
dim result as object
result = cmd1.ExecuteScalar()
dim count as int
count = Convert.ToInt32(result)
If count < 20 Then

Insert a record in sql database using vb.net datatable and datarow features

I am trying to insert a record in sql database using vb.net dataadapter, datatable, and datarow features. I use the following code but it gives me an error:
Object reference not set to an instance of an object
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=drpractice;Integrated Security=True")
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Try
cn.Open()
da.SelectCommand = New SqlCommand("SELECT * FROM [emp_tbl]", cn)
da.Fill(ds)
Dim dt As New DataTable
dt = ds.Tables("emp_tbl")
'Error in this line(Object reference not set to an instance of an object)'
Dim dr As DataRow = dt.NewRow()
dr.Item("emp_id") = TextBox1.Text.Trim
dr.Item("emp_name") = TextBox2.Text.Trim
dr.Item("salary") = TextBox3.Text.Trim
dr.Item("age") = TextBox4.Text.Trim
dr.Item("emp_group") = TextBox5.Text.Trim
dt.Rows.Add(dr)
da.Update(ds)
MsgBox("Record Successfully Inserted")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
check this out : Dim dr As DataRow = new dt.NewRow()
You have done everything good but change the following line:
da.Update(ds)
As following:
Dim ESCBuilder As SqlCommandBuilder = New SqlCommandBuilder(da)
ESCBuilder.GetUpdateCommand()
da.UpdateCommand = ESCBuilder.GetUpdateCommand()
da.Update(ds)
Based on the feedback here and elsewhere, the following code worked for me:
TestDataSet.GetChanges()
testTableAdapter.Fill(TestDataSet.log_test)
log_testDataGridView.Refresh()
What I needed to do was, create a new row, and go get the next value for the Primary Key(VARCHAR, NOT INT, because revisions got an "R" appended to the PK...not my rule...the rule of the company).
I wanted to put the refresh as close to the getting of the PK, which I had last after assigning values to the new datarow so it would get the latest Max +1.
So, I put the above code just before looking up the PK, and after assigning values to the datarow, other than PK. The code above caused the datarow to blank out. So, I put the above code just prior to the creation of the new DataRow.
For my code, this caused the code to get the latest data from the SQL table, then add the new datarow, and finally determine the last PK. Because the data used to populate the datarow is off my form, and there is no caclulations, the code runs fast enough for my needs. I suspect, if the connection to my database was slow, and/or, the number of people running the same process were substantial, I would have errors, such as duplicate PKs.
My answer to that would be to assign the datarow field values to variables, run the refresh, then assign the variables to the fields and save immediately.
Perhaps another way would be to get the new PK, then save an empty record, and then fill the record, except that enough of the fields in my table are REQUIRED so I might as well not try creating a blank record first.
Imports System.Data.SqlClient
Public Class Form4
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim str As String
Dim count As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New SqlConnection("server=SHREE-PC;database=Hospital;INTEGRATED SECURITY=SSPI;")
con.Open()
‘ cmd = New SqlCommand("select * from Doctor", con)
str = "insert into Doctor values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "' )"
cmd = New SqlCommand(str, con)
count = cmd.ExecuteNonQuery()
MessageBox.Show(count & " Record inserted")
con.close()
End Sub
Imports System.Data.SqlClient
Public Class Form4
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim str As String
Dim count As Integer
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
con = New SqlConnection("server=SHREE-PC;database=Hospital;INTEGRATED SECURITY=SSPI;")
con.Open()
cmd = New SqlCommand("select * from Patient", con)
cmd = New SqlCommand("Delete from Patient where Name ='" & TextBox1.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Address='" & TextBox2.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Dieses='" & TextBox3.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Patient_no=" & TextBox4.Text & "", con)
‘you can take any row in your program
count = cmd.ExecuteNonQuery()
MessageBox.Show("Record Deleted")
End Sub