I want to display result of select query in a DataGridView with where clause in query. The condition is specified in a label's value. i.e
select *
from hospital_details
where location_name= '" & Label6.Text & "'"
Following is the code
Public Sub fill()
Try
createConnection()
da = New SqlDataAdapter
Dim c As String
c = Label6.Text
comm.CommandText = "select * from hospital_details where location_name= '" & Label6.Text & "'"
da.SelectCommand = comm
da.Fill(ds, "hospital_details")
DataGridView2.DataSource = ds.Tables(0)
DataGridView2.DataMember = "hospital_details"
DataGridView2.ReadOnly = True
Catch ex As Exception
MsgBox("Error: " & ex.Source & ": " & ex.Message, MsgBoxStyle.OkOnly, "Connection Error !!")
End Try
End Sub
But its showing error : NullException
You can load data from sql server , follow the link
http://mssqlguid.blogspot.in/2013/07/how-to-load-data-into-datagridview-from.html
Related
In SQL Server, I have a table like this:
tableItem
------------------------
item | varchar (15),
price | numeric(18, 2)
In VB.NET, I have the code:
textbox1.text = "Book"
textbox2.text = 20.000,00
textbox2.text = format(val(textbox2.text), "#,##0.00")
Procedure Save :
dim sqlQuery as string = "insert into tableItem(item,price) values('" & textbox1.Text & "','" & textbox2.Text & "')"
Try
conn.open()
With Cmd
.Connection = Conn
.CommandType = CommandType.Text
.CommandText = sqlQuery
.ExecuteNonQuery
End With
Catch ex As Exception
MsgBox("Error at : " & ex.Message)
Finally
conn.close()
End Try
but I am getting the error:
Error converting data type varchar to numeric
If I change & textbox2.Text & to & val(textbox2.text) & in the query, the data is stored only 20 in price.
you are not allowed to assign 20.000,00 to a textbox2.Text property.
Try:
textbox2.text = "20.00"
On another note I would not pass the variables directly into the SQL insert query. Try the code below:
dim sqlQuery as string = "insert into tableItem(item,price) values(#item, #price)"
Try
conn.open()
With Cmd
.Parameters.AddWithValue("#item, textbox1.text)
.Parameters.AddWithValue("#price, textbox2.text)
.Connection = Conn
.CommandType = CommandType.Text
.CommandText = sqlQuery
.ExecuteNonQuery
End With
Catch ex As Exception
MsgBox("Error at : " & ex.Message)
End Try
conn.close()
Thanks for the help, but I found another way to keep using
format(val(texbox2.text), "#,##0")
on the keypress
and return to its original value (integer) using
Format(texbox2.text, "General Number")
I found this answer from other similar people's questions.
Thanks very much.
I am trying to develop a management system for dentists, this the system i am developing
THIS MY PROGRAM'S SCREENSHOT
when the dentist inputted a data on a textbox, it will be saved on the database and whenever the dentist insert a data again on that textbox, instead of replacing the older data with a newer data, it will store the data, making the cell store multiple data
and this is my code for adding data into the table
table name: teethhistory
database name: PatientManagementSystem
Private Sub txtURThirdMolar_KeyDown(sender As Object, e As KeyEventArgs) Handles txtURThirdMolar.KeyDown
If e.KeyCode = Keys.Enter Then
MySqlConn.Open()
query1 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd1 = New MySqlCommand(query1, MySqlConn)
reader = cmd1.ExecuteReader
If reader.HasRows Then
Dim i As Integer
With cmd
.Connection = MySqlConn
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar ='" & txtURThirdMolar.Text & "' WHERE Patient_ID_Number = " & lblID.Text
reader.Close()
i = .ExecuteNonQuery
End With
If i > 0 Then
MsgBox("Updated!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Failed", MsgBoxStyle.Information, "Failed")
End If
Else
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO teethhistory (Patient_ID_Number, Fullname, Up_Right_3rd_Molar )" &
"VALUES ('{0}' ,'{1}' ,'{2}')",
lblID.Text,
lblFullname.Text,
txtURThirdMolar.Text)
reader.close()
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Saved!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Saving failed.", MsgBoxStyle.Critical, "Failed")
End If
MySqlConn.close()
End If
End Sub
if you want to Append the Existing text In field with new data from textbox,use Update command as
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar = concat('" & txtURThirdMolar.Text & "',Up_Right_3rd_Molar) WHERE Patient_ID_Number = " & lblID.Text
for inserting values seperated by commas, just insert a comma before the string ion concat function.
hope i undestood your problem well and this solves it.
I am creating sort of like a database for work. I work as an IT Technician and we have many computers that come in for reimaging. We were losing many of them so I decided to make a "database" to keep tracks of everything. These computers come in with trouble tickets and I want the user to be able to search by ticket number or by serial number. My application tells me when the field is empty, it tells me when there are no results, but I can't figure out how to make it so that if it finds a result, I want it to display all fields of that row in textboxes. If it finds more than one results, I want it to show the most recent one (the rows also include the day it was brought in). Here is what I currently have:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim cmd As OleDbCommand
If txtSearch.Text = "" Then
MsgBox("No input", MsgBoxStyle.Exclamation, "Search")
txtSearch.Focus()
ElseIf InStr(txtSearch.Text, "'") Then
MsgBox("Invalid character: '", MsgBoxStyle.Critical, "Search")
txtSearch.Text = ""
txtSearch.Focus()
ElseIf rdoTicketNumber.Checked = True Then
Dim sql = "select * from Tickets where Ticket_Number = '" & txtSearch.Text & "'"
cmd = New OleDbCommand(sql, con)
con.ConnectionString = ("provider=microsoft.jet.oledb.4.0;data source=../Database.mdb")
con.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Try
If dr.Read = False Then
MsgBox("No Results", MsgBoxStyle.Information, "Search")
txtSearch.Text = ""
txtSearch.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
ElseIf rdoSerialNumber.Checked = True Then
Dim sql = "select * from Tickets where Asset_Serial = '" & txtSearch.Text & "'"
cmd = New OleDbCommand(sql, con)
con.ConnectionString = ("provider=microsoft.jet.oledb.4.0;data source=../Database.mdb")
con.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Try
If dr.Read = False Then
MsgBox("No Results", MsgBoxStyle.Information, "Search")
txtSearch.Text = ""
txtSearch.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End If
End Sub
Any and all help is appreciated. Thank you in advance!
If you really just want to filter your results of the query-string:
Dim sql = "select * from Tickets where Asset_Serial = '" & txtSearch.Text & "'"
To filter it for recent one, change it to something like this:
Dim sql = "select TOP(1) * from Tickets where Asset_Serial = '" & txtSearch.Text & "' ORDER BY <yourDateField> DESC"
That you should change <yourDateField> to name of that date field in your Tickets table, and also if you have just day of ticket and you want to filter the result to most recent in that date I suggest you this:
Dim sql = "select TOP(1) * from Tickets where Asset_Serial = '" & txtSearch.Text & "' ORDER BY <yourDateField> DESC, <yourPKField> DESC"
Hi I am trying to insert data into Navision database from a DataTable. That DataTable contain around 5000 records, if the records count is less then it's working fine but record count is around 5000 I am getting this error.
ERROR - unable to allocate an environment handle.
This is the code I am using
Public Function InsertToHHTTransferLine(ByVal dtTransferLn As DataTable, ByVal hhtNumber As String) As Integer
Dim result As Integer
Dim cn As OdbcConnection
Dim dtTransferLine As DataTable
cn = New OdbcConnection(ConnStr)
Dim SqlStr As String = ""
Try
cn.Open()
dtTransferLine = dtTransferLn
Dim DocType As String
DocType = "Purchase"
Dim cmd As OdbcCommand
Dim hhtNo As String
hhtNo = hhtNumber
If dtTransferLine.Rows.Count > 0 Then
For i As Integer = 0 To dtTransferLine.Rows.Count - 1
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "0" Then
DocType = "Purchase"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "1" Then
DocType = "Transfer Receipt"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "2" Then
DocType = "Transfer Shipment"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "3" Then
DocType = "Stock Count"
End If
Try
SqlStr = "INSERT INTO ""HHT & Navision Line""(""Document Type"",""Document No_"",""HHT No_"",""Line No_"",""Item No_"",""Document Quantity"",""Scan Quantity"",""Unit Price"",""Posted"") VALUES('" & DocType & "','" & dtTransferLine.Rows(i)("DOC_NO").ToString() & "','" & hhtNo & "','" & dtTransferLine.Rows(i)("LINE_NO").ToString() & "','" & dtTransferLine.Rows(i)("ITEM_NO").ToString() & "'," & dtTransferLine.Rows(i)("DOC_QTY").ToString() & "," & dtTransferLine.Rows(i)("SCAN_QTY").ToString() & "," & dtTransferLine.Rows(i)("UNIT_PRICE").ToString() & ",0)"
cmd = New OdbcCommand(SqlStr, cn)
result = cmd.ExecuteNonQuery()
Catch ex As Exception
If (ex.Message.IndexOf("Illegal duplicate key") <> -1) Then
CreateLog(SqlStr, "User1", "Duplicate()", ex.Message)
Else
CreateLog(SqlStr, "User1", "Other()", ex.Message)
End If
'CreateLog(SqlStr, "User1", "Other()", ex.Message)
End Try
Next
End If
Catch ex As Exception
CreateLog(SqlStr, "User1", "InsertToHHTTransferLine()", ex.Message)
result = -1
Finally
cn.Close()
cn.Dispose()
End Try
Return result
End Function
Could be that "cmd" variables need to be disposed before creating new ones?
At least this is the only thing I can see in the code where you are consuming resources in a loop depending on the number of records.
Anyway this should be easy to identify with a debugger, just figure out the line giving you the error, and that will lead you to the answer.
I've successfully taught myself how to pull some data from a MySQL database and bind it to a ListView control (ListViewCard).
Now I can't figure out how to use the SelectedIndexChanged event to inerate through the records and populate some other controls on my form (i.e, 7 textboxes, 2 comboboxes, and 2 datetimepickers).
Your help would be greatly appreciated. Here's my code:
Private Sub loadCard()
Try
'FOR MySQL DATABASE USE
'Dim dbQuery As String = ""
'Dim dbCmd As New MySqlCommand
'Dim dbAdapter As New MySqlDataAdapter
Dim dbTable As New DataTable
Dim i As Integer
If dbConn.State = ConnectionState.Closed Then
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
dbConn.Open()
End If
dbQuery = "SELECT *" & _
"FROM cc_master INNER JOIN customer ON customer.accountNumber = cc_master.customer_accountNumber " & _
"WHERE customer.accountNumber = '" & TextBoxAccount.Text & "'"
With dbCmd
.CommandText = dbQuery
.Connection = dbConn
End With
With dbAdapter
.SelectCommand = dbCmd
.Fill(dbTable)
End With
ListViewCard.Items.Clear()
For i = 0 To dbTable.Rows.Count - 1
With ListViewCard
.Items.Add(dbTable.Rows(i)("ccID"))
With .Items(.Items.Count - 1).SubItems
.Add(dbTable.Rows(i)("ccNumber"))
.Add(dbTable.Rows(i)("ccExpireMonth"))
.Add(dbTable.Rows(i)("ccExpireYear"))
End With
End With
Next
Catch ex As MySqlException
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
dbConn.Close()
End Sub