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

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

Related

fill datagridview based on combobox selected item which depends on another selected combobox from database

I am creating an add student windows form and it contains two comboboxes. the first one contains semester of the student and the second one contains the course code based on the value of semester. the problem I'm facing is that i also have a datagridview and i want to populate it with data of students contained in table of course code and as soon as i click semester combobox value of course code combobox changes, as soon as it changes, I want to load data of datagridview but it shows the error which basically is cannot convert datarows to string but when I use ComboBox1.ValueMember and load datagridview on clicking button it works fine. but when i load datagridview on combobox change it shows error.
this code works fine
Imports System.Data.OleDb
Public Class AddStudent
Dim con As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\Students.accdb")
Dim con1 As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\Users.accdb")
Private Sub AddStudent_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.Open()
Dim cmd As New OleDbCommand("Select stud_roll From " + ComboBox1.SelectedValue + " where stud_roll = #roll1", con)
cmd.Parameters.AddWithValue("roll1", TextBox2.Text)
Dim myreader As OleDbDataReader = cmd.ExecuteReader
If myreader.Read() Then
con.Close()
MessageBox.Show("Student Inserted before")
Else
con.Close()
Dim cmd1 As New OleDbCommand("Insert into " + ComboBox1.SelectedValue + "(stud_roll,stud_name,date_of_birth,course,gender,mobile_no,semester) Values(#roll,#name,#dob,#course,#gender,#mobile,#semester)", con)
cmd1.Parameters.AddWithValue("roll", Convert.ToInt32(TextBox2.Text))
cmd1.Parameters.AddWithValue("name", TextBox1.Text)
cmd1.Parameters.AddWithValue("dob", DateTimePicker1.Value.Date)
cmd1.Parameters.AddWithValue("course", ComboBox1.SelectedValue)
cmd1.Parameters.AddWithValue("gender", ComboBox2.SelectedItem)
cmd1.Parameters.AddWithValue("mobile_no", MaskedTextBox1.Text)
cmd1.Parameters.AddWithValue("semester", Convert.ToInt32(ComboBox3.SelectedItem))
con.Open()
cmd1.ExecuteNonQuery()
con.Close()
MessageBox.Show("Records inserted successfully")
End If
con.Open()
Dim cmd3 As New OleDbCommand("Select stud_roll, stud_name, date_of_birth, course, gender,mobile_no, semester From " + ComboBox1.SelectedValue + "", con)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd3
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
End Sub
Private Sub Label8_Click(sender As Object, e As EventArgs) Handles Label8.Click
AddTeacher.Show()
End Sub
Private Sub ComboBox3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox3.SelectedIndexChanged
con1.Open()
Dim cmd As New OleDbCommand("Select course_code From courses Where semester= " + ComboBox3.SelectedItem + "", con1)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "course_code"
ComboBox1.ValueMember = "course_code"
con1.Close()
End Sub
Private Sub Label14_Click(sender As Object, e As EventArgs) Handles Label14.Click
Courses.Show()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
End Class
when i load after combobox change like this, it shows error :- System.InvalidCastException: 'Operator '+' is not defined for string "Select stud_name, stud_roll From" and type 'DataRowView'.'
which is because of datarowview type conversion
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
con.Open()
Dim cmd3 As New OleDbCommand("Select stud_roll, stud_name, date_of_birth, course, gender,mobile_no, semester From " + ComboBox1.SelectedValue + "", con)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd3
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
End Sub
please help me with this.
1. Make sure to give the controls meaningful names: it will make your life easier. "ComboBox1" is not a meaningful name ;)
2. Don't create a single instance of a database connection that is re-used: you are meant to create the connection object, use it, and then dispose of it. There are mechanisms behind the scenes to make this efficient (Connection Pooling). There is an example of how to do it in a previous answer of mine.
3. You don't need to open and close the connection for da.Fill(dt): it does it automatically.
4. Because ComboBox1.SelectedValue comes from a datatable, you will need to extract the column of that datarowview, something like:
Dim tableName = DirectCast(ComboBox1.SelectedItem, DataRowView).Row.Field(Of String)("course_code")
Dim cmd3 As New OleDbCommand("Select stud_roll, stud_name, date_of_birth, course, gender,mobile_no, semester From [" & tableName & "]", con)

How to feed results of SQL statement into a GridView, not the SQL statement itself?

This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is. Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox. Here is my code.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
sqlConn.Open()
Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
Dim dsColumns As New DataSet
Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)
daAdapter.Fill(dsColumns)
If dsColumns.Tables(0).Rows.Count > 0 Then
ListBox1.Items.Clear()
For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim SqlStr As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim myItem As String
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
connection = New SqlConnection(connetionString)
'Dim iIndex As Integer = ListBox1.SelectedIndex
myItem = ListBox1.SelectedItem
SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
adapter = New SqlDataAdapter(SqlStr, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I guess the problem is passing the SQL to the GridView. When I select the first Item, I see this in my GridView.
SELECT [OrderID]
,[CustomerID]
,[EmployeeID]
,[OrderDate]
,[RequiredDate]
,[ShippedDate]
,[ShipVia]
,[Freight]
,[ShipName]
,[ShipAddress]
,[ShipCity]
,[ShipRegion]
,[ShipPostalCode]
,[ShipCountry]
FROM [Test].[dbo].[Orders]
That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.
This is what I see now.
I want to see something more like this.
Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns. Now, if I stretch out the form window, the GridView stays static.
You need to actually run the retrieved Sql statement:
sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
Dim cmd As New SqlCommand(sqlstr, connection)
Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
cmd.Dispose()
adapter = New SqlDataAdapter(sqlstr_report, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Use the .Anchor property of the DataGridView to make it resize with the form

VB.Net SQL Count Statement into a label

I'm trying to count the students whose teacher where teacher = '" & lblTeacher.Text & "'"
EXAMPLE :
Public Class Form1
Dim conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Richard\Desktop\Dbase.mdb"
Dim con As New OleDbConnection
Dim da, da1 As New OleDbDataAdapter
Dim dt, dt1 As New DataTable
Dim sql As String
Dim ds As New DataSet
Public Sub display()
sql = "select * from Info"
dt.Clear()
con.Open()
da = New OleDbDataAdapter(sql, con)
da.Fill(dt)
con.Close()
DataGridView1.DataSource = dt.DefaultView
End Sub
Public Sub count()
sql = "select COUNT(name) from Info where teacher = '" & lblTeacher.Text & "'"
da1 = New OleDbDataAdapter(sql, con)
ds.Clear()
con.Open()
da.Fill(ds)
lblCount.Text = ds.Tables(0).Rows.Count.ToString
con.Close()
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = conn
display()
End Sub
Private Sub DataGridView1_Click(sender As System.Object, e As System.EventArgs) Handles DataGridView1.Click
lblTeacher.Text = DataGridView1.CurrentRow.Cells("teacher").Value.ToString
count()
End Sub
End Class
1:
Try this instead of your current count() method. Pay special attention to my comments; they address some poor practices from the original code:
' Better functional style: accept a value, return the result
Public Function GetStudentCount(teacher As String) As Integer
'**NEVER** use string concatenation to put data into an SQL command!!!
Const sql As String = "select COUNT(name) from Info where teacher = ?"
'Don't try to re-use the same connection in your app.
' It creates a bottleneck, and breaks ADO.Net's built-in connection pooling,
' meaning it's more likely to make object use *worse*, rather than better.
'Additionally, connection objects should be created in a Using block,
' so they will still be closed if an exception is thrown.
' The original code would have left the connection hanging open.
Using con As New OleDbConnection(conn), _
cmd As New OleDbCommand(sql, con)
'This, rather than string concatenation, is how you should put a value into your sql command
'Note that this NEVER directly replaces the "?" character with the parameter value,
' even in the database itself. The command and the data are always kept separated.
cmd.Parameters.Add("teacher", OleDbType.VarChar).Value = teacher
con.Open()
' No need to fill a whole dataset, just to get one integer back
Return DirectCast(cmd.ExecuteScalar(), Integer)
'No need to call con.Close() manually. The Using block takes care of it for you.
End Using
End Function
Here it is again, without all the extra comments:
Public Function GetStudentCount(teacher As String) As Integer
Const sql As String = "select COUNT(name) from Info where teacher = ?"
Using con As New OleDbConnection(conn), _
cmd As New OleDbCommand(sql, con)
cmd.Parameters.Add("teacher", OleDbType.VarChar).Value = teacher
con.Open()
Return DirectCast(cmd.ExecuteScalar(), Integer)
End Using
End Function
Call it like this:
Private Sub DataGridView1_Click(sender As System.Object, e As System.EventArgs) Handles DataGridView1.Click
lblTeacher.Text = DataGridView1.CurrentRow.Cells("teacher").Value.ToString()
lblCount.Text = GetStudentCount(lblTeacher.Text).ToString()
End Sub

how to add data in sql database with datagridview

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.

selecting in vb.net with ms access database

I want to select some data in my table and I use this code :
Public Class frmLogin
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Dim t As New DataTable
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
Dim cmd As OleDbCommand
Dim reader As OleDbDataReader = Nothing
Dim tuser As String = txtUsername.Text
Dim sql As String = "SELECT * FROM dosen WHERE nip=tuser"
Try
cmd = New OleDbCommand(sql, conn)
reader = cmd.ExecuteReader()
While reader.Read
MessageBox.Show(reader.GetString(0).ToString & _
vbTab & vbTab & reader.GetString(1).ToString)
End While
Finally
If reader IsNot Nothing Then reader.Close()
End Try
End Sub
But there is an error in reader = cmd.ExecuteReader() line. Anyone can help me?
Correct the mistakes. The code should be
Dim reader As OleDbDataReader ' no need for nothing
Dim adapter As New OleDbDataAdapter()
Dim sql As String = "SELECT * FROM dosen WHERE nip='" & tuser & "'"
tuser is a variable, not the content