System.Data.DataRowView when inserting to sql server - vb.net

i'm trying to insert selected value from a listbox and the value is System.Data.DataRowView in the sql server, I'm kinda new to this vb thing. can you help...
why is that?
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'AccountsC20DataSet.ProductMast' table. You can move, or remove it, as needed.
Me.ProductMastTableAdapter.Fill(Me.AccountsC20DataSet.ProductMast)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles SAVE.Click
Try
con.ConnectionString = "Data Source = OMAR;Initial Catalog=AccountsC20;Persist Security Info=True;User ID=ofamo;Password="
con.Open()
cmd.Connection = con
Dim Selected = ListBox1.SelectedValue.ToString()
cmd.CommandText = "Insert into SInvoice Values('" + Selected + "',0,1,1,1.000000,0.000000,'04/04/2019 08:45:08',0.000000,0.000000,'',0,1,1,1,1,'04/04/2019 08:45:08','',1.000000,1,0,'','b',0.000000,5,0.000000,0.000000,'Nos',1.000000,'','','','','','','','','','','','','','','','','','','','','',0,3,'SIV-',1,1,1,1,1,1,0.000000)"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
End Sub
End Class
What i'm doing wrong here.....

Related

Refresh a datagrid in another form

I am using VB to make something to change records in a database. I have a table called tblCustomers. When the user clicks a button on the homeForm, a new form called FormNewCustomer appears which has text boxes for the user to input info to put in the database. After submitting it, the data does get inserted, but it doesn't show in the datagridview.
This is my code:
Imports System.Data.OleDb
Public Class FormNewCustomer
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=ProgramDatabase.accdb"
Public conn As New OleDbConnection(connstring)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Me.Close()
End Sub
Private Sub btnCopy_Click(sender As Object, e As EventArgs) Handles btnCopy.Click
If txtCustomerName.Text = "" Or txtAC.Text = "" Then
MsgBox("Enter a Customer Name and a Customer Reference.")
Else
conn.Open()
Dim SqlQuery As String = "INSERT INTO tblCustomers (CustomerName,AC,Address,Phone,Email) VALUES (#CustomerName,#AC,#Address,#Phone,#Email)"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Parameters.AddWithValue("#CustomerName", txtCustomerName.Text)
.Parameters.AddWithValue("#AC", txtAC.Text)
.Parameters.AddWithValue("#Address", txtAddress.Text)
.Parameters.AddWithValue("#Phone", txtPhone.Text)
.Parameters.AddWithValue("#Email", txtEmail.Text)
.Connection = conn
.ExecuteNonQuery()
End With
conn.Close()
MsgBox("Successfully added new Customer.")
FormHome.DataGridView1.Refresh()
Me.Close()
End If
End Sub
End Class
Try this Code:
Dim objDataGridView As YourFormClassName = New YourFormClassName
objDataGridView.ShowDialog()

Application with two forms is not showing

I am creating a form application using Visual Studio Express VB 2008 and SQL server 2008. I have two forms. When the program start is not showing me any form. What is to be done that I could use two forms as one program. For example, in one form I want to insert data type state, city .. and the other to use the same information for something else. But like I said, my first step is to see both forms in one program. What should I do to make it work
Imports System.Data.Sql
Imports System.Data.SqlClient
' This is my main form called form1 and through it I want to call a form called Country. Belonging to the same project. How to call a form ,,country,, that I could use
Public Class Form1
Dim objDS As New DataSet
Dim objDA As New SqlDataAdapter
Public Sqlcon As New SqlConnection With {.connectionString = "server=XXX\MSSQL2008;database=TEST;Trusted_Connection=True;"}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If hasConnection() = True Then
MessageBox.Show("uspijesno povezano sa bazom")
End If
getSelc()
End Sub
Public Function hasConnection() As Boolean
Try
Sqlcon.Open()
Sqlcon.Close()
Return True
Catch ex As Exception
MessageBox.Show("Niste povezani sa bazom")
Return False
End Try
End Function
Public Function selc()
Dim objDS = New DataSet
Dim objDA As New SqlDataAdapter
Sqlcon.Close()
Sqlcon.Open()
Dim exCommand As String = ""
Dim myCommand As New SqlCommand
Dim commitTransaction = Sqlcon.BeginTransaction
Try
myCommand = New SqlCommand("EXECUTE " & "regionSelect" & " '" & txtID.EditValue & "', '" & txtShortN.EditValue & "', N'" & txtRegion.EditValue & "', '" & txtStatus.EditValue & "'", Sqlcon)
myCommand.Transaction = commitTransaction
objDA.SelectCommand = myCommand
objDA.Fill(objDS)
commitTransaction.Commit()
Sqlcon.Close()
MessageBox.Show("Podaci su uspijesno poslati")
Catch ex As Exception
MessageBox.Show(ex.Message)
commitTransaction.Rollback()
End Try
End Function
Private Sub SimpleButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
'insert()
End Sub
Private Sub btnConfirm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
getSelc()
End Sub
Public Function getSelc()
objDS = New DataSet
Dim com As New SqlCommand
Sqlcon.Close()
Sqlcon.Open()
GridControl1.DataSource = Nothing
Try
com = New SqlCommand("EXECUTE rS '" & txtID.Text & " ' , ' " & txtRegion.Text & "' , '" & txtShortN.Text & "', ' " & txtStatus.Text & " ' ", Sqlcon)
'com = New SqlCommand("SELECT * FROM tblRegion", Sqlcon)
objDA.SelectCommand = com
objDA.Fill(objDS)
com.CommandType = CommandType.StoredProcedure
GridControl1.DataSource = objDS.Tables(0)
objDA.Dispose()
com.Dispose()
Sqlcon.Close()
MessageBox.Show("Im here")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'GridControl1.DataSource = Nothing
'objDS.Tables(0).Rows.Clear()
End Function
Private Sub SimpleButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton4.Click
getSelc()
Dim newRow As DataRow
newRow = objDS.Tables(0).NewRow
newRow.Item(0) = txtID.EditValue
newRow.Item(1) = txtShortN.EditValue
newRow.Item(2) = txtRegion.EditValue
newRow.Item(3) = txtStatus.EditValue
objDS.Tables(0).Rows.Add(newRow)
End Sub
Private Sub SimpleButton3_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton3.Click
End Sub
Private Sub SimpleButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton1.Click
Country.Show() ' => Is this a good way, and is there any better way and more efficient
End Sub
End Class
You cannot load more than one form on Application Startup. You have to load any one form first then show others from its Form_Load event.
Private Sub StartupForm_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim form2 As New Form2
form2.Show()
Dim form3 As New Form3
form3.Show()
End Sub
Or you can load forms manually on Button Click.
Set the Form1 as a StartupForm from the Project Property Window.
Now, Add a button in your first form button1 and write down some code to display another form.
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
Dim form2 As New Form2
form2.Show()
End Sub
Another one is calling main method. For that you need to assign Main method in your Project Property Window
Module mainModule
Sub Main()
Dim form2 As New Form2
form2.Show()
Dim form3 As New Form3
form3.ShowDialog()
End Sub
End Module

Visual Basic.Net 2010 Exception Error meaning

Can anyone Help me to figure out whats the meaning of this error statement.I keep getting this error statement:-
index (zero based) must be greater than or equal to zero and less than the size of the argument list
Below is my coding
Imports System.Data.OleDb
Public Class form2
Dim Mycn As OleDbConnection
Dim Command As OleDbCommand
Dim icount As Integer
Dim SQLstr As String
Private Sub Button1_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Mycn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\lenovo\Documents\Final year stuff\BookStoreDb.mdb;")
Mycn.Open()
SQLstr = String.Format("INSERT INTO login VALUES('{0}','{1}','{2}','{3}','{4}')", TextBox1.Text, TextBox2.Text)
Command = New OleDbCommand(SQLstr, Mycn)
icount = Command.ExecuteNonQuery
MessageBox.Show(icount)
Catch ex As Exception
MessageBox.Show(ex.Message & " - " & ex.Source)
Mycn.Close()
End Try
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
As Plutonix suggested, just specify the two fields.
You can combine that with the parameters so you are also safe from injection attacks.
Try the following:
SQLstr = String.Format("INSERT INTO Login (User, Password) VALUES ('{0}','{1}')", TextBox1.Text, TextBox2.Text)
Command = New OleDbCommand(SQLstr, Mycn)

Data updation and deletion error

I have a DataGrid and many text fields to add data into the database. When i add a new data, it gets updated in the database and in the data grid.But when i delete the data, it gets deleted only from the database. It doesn't get updated in the data grid.
When i try to update the data, it updates only one record at a time.when i try for another record it gives me a error "The variable name '#date' has already been declared. Variable names must be unique within a query batch or stored procedure." I have to close and reopen the form to update a new record.
Imports System.Data.SqlClient
Public Class Form
Dim con As New SqlClient.SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlDataAdapter1.Fill(DataSet11)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles newbtn.Click
If RegNoTextBox.Text <> "" Then
cmd.Connection = con
con.Open()
cmd.CommandText = "insert into WaterProofing(Date,RegNo) values ('" & DateDateTimePicker.Value & "','" & RegNoTextBox.Text & "')"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
Else
MessageBox.Show("Please enter registration number")
End If
End Sub
//updation
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
cmd.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
cmd.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
cmd.Connection = con
con.Open()
cmd.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Updated!")
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
cmd.Connection = con
con.Open()
cmd.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Deleted!")
End Sub
Sub showdata()
SqlDataAdapter1.Fill(DataSet11, "WaterProofing")
With DataGridView
.Update()
End With
End Sub
End Class
Please help me in deletion and updating.
You're adding parameters before declaring CommandText at Button2_Click
Try it in this way:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
command.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
command.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
command.ExecuteNonQuery()
con.Close()
Call showdata()
MessageBox.Show("Details Updated!")
Catch ex as Exception
MessageBox.Show(ex.Message)
End try
End Sub
UPDATE
Basically you have to do the same thing when you load the DataGridView for the first time in order to refresh the DataGridView with the current data from database after deleting or updating records, so your ShowData Sub might look something like this
Private Sub ShowData()
Dim Connection As SqlConnection
Connection = New SqlConnection("YourConnectionString")
Try
Connection.Open()
Dim SQL As String = "SELECT Field1, Field2, Field3 FROM Table"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView.DataSource = DS.Tables(0)
DataGridView.Refresh()
Catch ex As Exception
MessageBox(ex.Message)
Finally
Connection.Close()
End Try
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
command.ExecuteNonQuery()
con.Close()
Call ShowData_Delete()
MessageBox.Show("Details Deleted!")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub ShowData_Delete()
Dim Connection As SqlConnection
Try
Connection = New SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Connection.Open()
Dim SQL As String = "SELECT * from WaterProofing"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView1.DataSource = DS.Tables(0)
DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Connection.Close()
End Try
End Sub

SQL connection error showing INVALID OBJECT NAME

I have done follwing coding but it shows error
Invalid object name 'sanket'
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim da As SqlDataAdapter
Dim ds As New DataSet
Dim str As String
Private Sub ConnectToSQL()
Try
con.ConnectionString = "Data Source=SA_N_KET-PC\SQLEXPRESS;Initial Catalog=repeat;Integrated Security=true;"
con.Open()
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
'DoNothing.
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'CryrptDataSet.sanket' table. You can move, or remove it, as needed.
Me.SanketTableAdapter.Fill(Me.CryrptDataSet.sanket)
ConnectToSQL()
End Sub
Public Sub exe()
str = "insert into sanket(n)values ('" & TextBox1.Text & "')"
da = New SqlDataAdapter(Str, con)
da.Fill(ds, "sanket")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
exe()
End Sub
End Class