show row contents in datagridview - vb.net

my problem is when I add account the account successfully added, but the row content is not showing in my datagridview.
this is the code for my add button in addaccount form. "frmaddaccount is the name of the form and button1 is the button when i add.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim un = TextBox1.Text
Dim pw = TextBox2.Text
Dim ac = lbluser.Text
Dim fn = TextBox4.Text
Dim ln = TextBox5.Text
Dim age = TextBox6.Text
Dim val = "accountId_seq.nextval,'" & un & "','" & pw & "','" & ac & "','" & fn & "','" & ln & "','" & age & "'"
Dim sql = "insert into d_account values(" & val & ")"
con.Connect()
con.Manipulate(sql)
accountLog()
MessageBox.Show("Account successfulyy added!")
display()
con.Close()
clear()
Catch ex As Exception
MessageBox.Show("ERROR:" & vbCrLf & " " & vbCrLf & " 1. Complete the required information " & vbCrLf & " 2. Make sure that you input correct datatypes " & vbCrLf & " 3. Username already exist")
End Try
End Sub
Private Sub frmaddAccount_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Connect()
datagridview1.DataSource = dtb
dtb.Columns.Add("Username")
dtb.Columns.Add("Password")
dtb.Columns.Add("Access")
dtb.Columns.Add("First Name")
dtb.Columns.Add("Last Name")
dtb.Columns.Add("Age")
display()
con.Close()
End Sub
Sub display()
con.Connect()
Dim sql = "select * from d_account order by d_un asc"
odr = con.Retrieve(sql)
dtb.Clear()
While (odr.Read)
Dim un = odr.GetOracleValue(1)
Dim pw = odr.GetOracleValue(2)
Dim ac = odr.GetOracleValue(3)
Dim fn = odr.GetOracleValue(4)
Dim ln = odr.GetOracleValue(5)
Dim age = odr.GetOracleValue(6)
dtb.Rows.Add(un, pw, ac, fn, ln, age)
End While
con.Close()
End Sub
and this is the code in manageaccount form where my datagridview place.. frmmanageaccount is the name of the form.
Private Sub frmmanageAccount_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Connect()
DataGridView1.DataSource = dtb
dtb.Columns.Add("Account ID")
dtb.Columns.Add("Username")
dtb.Columns.Add("Password")
dtb.Columns.Add("Access")
dtb.Columns.Add("First Name")
dtb.Columns.Add("Last Name")
dtb.Columns.Add("Age")
display()
con.Close()
Label14.Text = DataGridView1.RowCount()
Dim i As Integer
For i = 0 To DataGridView1.Columns.Count - 1
DataGridView1.Columns.Item(i).SortMode = DataGridViewColumnSortMode.Programmatic
Next
Me.DataGridView1.DefaultCellStyle.Font = New Font("CAmbria", 10)
Me.DataGridView1.ColumnHeadersDefaultCellStyle.Font = New Font("CAmbria", 12)
Me.DataGridView1.DefaultCellStyle.SelectionBackColor = Color.FromArgb(129, 207, 224)
End Sub
Sub display()
con.Connect()
Dim sql = "select * from d_account where d_ac = 'user' order by d_un asc"
odr = con.Retrieve(sql)
dtb.Clear()
While (odr.Read)
Dim id = odr.GetOracleValue(0)
Dim un = odr.GetOracleValue(1)
Dim pw = odr.GetOracleValue(2)
Dim ac = odr.GetOracleValue(3)
Dim fn = odr.GetOracleValue(4)
Dim ln = odr.GetOracleValue(5)
Dim age = odr.GetOracleValue(6)
dtb.Rows.Add(id, un, pw, ac, fn, ln, age)
Label14.Text = DataGridView1.RowCount()
End While
con.Close()
End Sub

Related

Read String From Serial port Visual Basic

Imports System.IO.Ports
Imports System.Text
Public Class Form4
Dim myStringBuilder As String
Dim insert As New OleDb.OleDbCommand
Dim cnn As New OleDb.OleDbConnection
Public user As String
Private Sub Serialport2_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort2.DataReceived
myStringBuilder = SerialPort2.ReadExisting()
Me.Invoke(New EventHandler(AddressOf UpdateControls))
End Sub
Private Sub UpdateControls(ByVal sender As Object, ByVal e As EventArgs)
Dim A As String = myStringBuilder
Dim Sqql As String
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
insert.Connection = cnn
Dim dt As New DataTable
Sqql = "SELECT * FROM `FileInfo` WHERE `File ID`='" & A & "'"
Dim cmd As New OleDb.OleDbDataAdapter(Sqql, cnn)
cmd.Fill(dt)
Dim i As Integer = dt.Rows.Count
Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)
If i = 1 Then
insert.CommandText = "INSERT INTO `File Log`(File ID,Name,Information,Time,Date) " & _
" VALUES('" & A & "','" & dt.Rows(0).Item("Name") & "','" & user & " telah" & dt.Rows(0).Item("Status") & "File" & "','" &
_
TimeOfDay & "','" & todaysdate & "')"
textBox1.Text += dt.Rows(0).Item("Name") & " " & TimeOfDay & " " & todaysdate &
Environment.NewLine
textBox1.Select(textBox1.TextLength, 0)
textBox1.ScrollToCaret()
insert.ExecuteNonQuery()
myStringBuilder = ""
Else
myStringBuilder = ""
textBox1.Text += A & Environment.NewLine
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnn = New OleDb.OleDbConnection
cnn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\data.mdb"
If SerialPort2 IsNot Nothing Then
SerialPort2.Close()
End If
SerialPort2 = My.Computer.Ports.OpenSerialPort("COM27", 9600, Parity.None, 8, StopBits.One)
textBox1.Text = "-- Door Have Open -- " & Environment.NewLine & Environment.NewLine
End Sub
Private Sub textBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textBox1.TextChanged
End Sub End Class
in my serial monitor view it will appear correctly but in visual basic it will auto break line and not display the string in one line.
I Tried other method like serialport.readline() but nothing happen.
If you are having issues with extracting data from your serial port you could try this:
Sub SerialPort_DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Dim currentSP As SerialPort = Convert.ChangeType(sender, GetType(SerialPort))
Dim strBuilder As System.Text.StringBuilder = New System.Text.StringBuilder()
For index = 1 To currentSP.BytesToRead
strBuilder.Append(Convert.ChangeType(currentSP.ReadByte(), GetType(Char)))
Next
' Have a global string to allow the threads to have a shared resource
myString = strBuilder.ToString()
Me.Invoke(New EventHandler(AddressOf UpdateControls))
End Sub
It should work the same way as the SerialPort.ReadLine(), this approach also lets you manipulate the data however you want. Instead of working with a string you could always work the data like this:
Dim buffer As Byte() = New Byte(currentSP.BytesToRead) {}
buffer(index) = Convert.ChangeType(currentSP.ReadByte(), GetType(Byte))
So instead of appending the Char to the String you can add the Byte to the buffer
Dim str As String = MyCOMPort.ReadExisting()
If Me.InvokeRequired Then
Me.Invoke(New dlUpdateText(AddressOf updatetext), str)
Else
updatetext(str)
End If

Updating data in gridview using vb.net

First I populated the datagridview by data of sqlserver 2008 database table, now i have muliple rows in datagridview containing data, i am trying to update any row but, in the database table it replaces other rows data by the row data that iam trying to update
the code for update statement is given below
Plz help me
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" &
dgvEmpDetail.Rows(0).Cells(1).Value & "', Experience ='" &
dgvEmpDetail.Rows(0).Cells(2).Value & "', Skills='" &
dgvEmpDetail.Rows(0).Cells(3).Value
& "' where Emp_ID = '" & dgvEmpDetail.Rows(0).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
You've hard coded the row - dgvEmpDetail.Rows(0).
I imagine you are calling this in a loop. You should do something like:
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" & dgvEmpDetail.Rows(i).Cells(1).Value & "', Experience ='" & dgvEmpDetail.Rows(i).Cells(2).Value & "', Skills='" & dgvEmpDetail.Rows(i).Cells(3).Value()& "' where Emp_ID = '" & dgvEmpDetail.Rows(i).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Next
Your code is susceptible to SQL injection. You should put the update SQL in to a stored procedure - its faster and safer!
Protected Sub Page_Load()
If Not Page.IsPostBack Then
' Create a new table.
Dim taskTable As New DataTable("TaskList")
' Create the columns.
taskTable.Columns.Add("Id", GetType(Integer))
taskTable.Columns.Add("Description", GetType(String))
taskTable.Columns.Add("IsComplete", GetType(Boolean))
'Add data to the new table.
For i = 0 To 19
Dim tableRow = taskTable.NewRow()
tableRow("Id") = i
tableRow("Description") = "Task " + i.ToString()
tableRow("IsComplete") = False
taskTable.Rows.Add(tableRow)
Next
'Persist the table in the Session object.
Session("TaskTable") = taskTable
'Bind data to the GridView control.
BindData()
End If
End Sub
Protected Sub TaskGridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
TaskGridView.PageIndex = e.NewPageIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
'Set the edit index.
TaskGridView.EditIndex = e.NewEditIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowCancelingEdit()
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Retrieve the table from the session object.
Dim dt = CType(Session("TaskTable"), DataTable)
'Update the values.
Dim row = TaskGridView.Rows(e.RowIndex)
dt.Rows(row.DataItemIndex)("Id") = (CType((row.Cells(1).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("Description") = (CType((row.Cells(2).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("IsComplete") = (CType((row.Cells(3).Controls(0)), CheckBox)).Checked
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Private Sub BindData()
TaskGridView.DataSource = Session("TaskTable")
TaskGridView.DataBind()
End Sub
</script>
I have a access connection with textbox as data feeder to database change it to SQL if u want. The code is:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form2
Dim conaccess As New OleDbConnection
Dim conreader As OleDbDataReader
Dim concmd As New OleDbCommand
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.EditMode = False
conaccess.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=d:\vijay.mdb"
conaccess.Open()
loadGrid()
End Sub
Private Sub loadGrid()
Dim access As String
access = "select * from vijay"
Dim DataTab As New DataTable
Dim DataAdap As New OleDbDataAdapter(access, conaccess)
DataAdap.Fill(DataTab)
DataGridView1.DataSource = DataTab
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
Dim no As String
no = "select Max(ID) from vijay"
Dim concmd As New OleDbCommand(no, conaccess)
conreader = concmd.ExecuteReader
If (conreader.Read) Then
If (IsDBNull(conreader(0))) Then
id_txt.Text = "1"
Else
id_txt.Text = conreader(0) + 1
End If
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End If
End Sub
Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Try
id_txt.Text = DataGridView1.Item(0, i).Value
name_txt.Text = DataGridView1.Item(1, i).Value
class_txt.Text = DataGridView1.Item(2, i).Value
gen_txt.Text = DataGridView1.Item(3, i).Value
branch_txt.Text = DataGridView1.Item(4, i).Value
age_txt.Text = DataGridView1.Item(5, i).Value
Catch ex As Exception
End Try
End Sub
Private Sub del_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles del_btn.Click
Dim delcmd As New OleDbCommand("delete from vijay where id=" & id_txt.Text & " ", conaccess)
delcmd.ExecuteNonQuery()
MsgBox("Record is deleted")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
Dim access As String = String.Format("INSERT INTO vijay (Name,Class,Branch,Gender,Age) VALUES('{0}','{1}','{2}','{3}','{4}')", name_txt.Text, class_txt.Text, branch_txt.Text, gen_txt.Text, age_txt.Text)
concmd.Connection = conaccess
concmd.CommandText = access
concmd.ExecuteNonQuery()
MsgBox("Record Successfully Saved")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub up_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles up_btn.Click
Dim access As String
access = "UPDATE vijay SET Name = '" & name_txt.Text & "', Age = '" & age_txt.Text & "', Gender ='" & gen_txt.Text & "' , Branch ='" & branch_txt.Text & "' , Class = '" & class_txt.Text & "' where id=" & id_txt.Text & ""
Dim cmd As New OleDbCommand(access, conaccess)
cmd.ExecuteNonQuery()
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
End Class
Use looping and parameter (to handle sql injection):
con.Open() 'Open connection to database
'Looping throung dgv
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
If IsDBNull(dgvEmpDetail.Rows(i).Cells("Emp_ID").Value) Then Exit For
Dim cmd As New SqlCommand("Update EmployeeDetail Set [Salary] = ?, [Experience]=?, [Skills]=? WHERE [Emp_ID] =?", con)
With cmd.Parameters
.AddWithValue("#Salary", dgvEmpDetail.Rows(i).Cells("Salary").Value )
.AddWithValue("#Experience", dgvEmpDetail.Rows(i).Cells("Experience").Value )
.AddWithValue("#Skills", dgvEmpDetail.Rows(i).Cells("Skills").Value )
.AddWithValue("#Emp_ID", dgvEmpDetail.Rows(i).Cells("Emp_ID").Value )
End With
cmd.ExecuteNonQuery()
Next i
con.Close() 'Close connection with Database

Calling and executing a stored procedure from sql into a vb.net textbox

I have created the following stored procedure in SQL Server:
CREATE Procedure CalcTotal
#InvoiceID Varchar(4)
As
Declare #Total int
Begin
SELECT
#Total = (TransportFee + EquipmentFee + LabourFee)
FROM
Invoice
WHERE
InvoiceID = #invoiceID
UPDATE Invoice
SET Total = #Total
WHERE InvoiceID = #invoiceID
END
My code for my form on Visual Basic are:
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Invoice
Dim sqlConn As New SqlConnection With {.ConnectionString = "Data Source=Hamsheed;Initial Catalog=assignment;Integrated Security=True"}
Dim sqlstr As String = "Select * From Invoice"
Dim MaxRows As Integer
Dim RowIndex As Integer = 0
Dim dt As New DataTable
Private Sub Invoice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim DataAdapter As New SqlDataAdapter(sqlstr, sqlConn)
DataAdapter.Fill(dt)
DataAdapter.Dispose()
MaxRows = dt.Rows.Count
InvoiceDetails()
cmbSearch.DataSource = dt
cmbSearch.DisplayMember = "FirstName"
End Sub
Sub InvoiceDetails()
txtInvoiceID.Text = CStr(dt.Rows(RowIndex)("InvoiceID"))
txtClientID.Text = CStr(dt.Rows(RowIndex)("ClientID"))
txtEmployeeID.Text = CStr(dt.Rows(RowIndex)("EmployeeID"))
txtFillInDate.Text = CStr(dt.Rows(RowIndex)("FillInDate"))
txtTransportFee.Text = CStr(dt.Rows(RowIndex)("TransportFee"))
txtEquipmentFee.Text = CStr(dt.Rows(RowIndex)("EquipmentFee"))
txtLabourFee.Text = CStr(dt.Rows(RowIndex)("LabourFee"))
txtTotal.Text = CStr(dt.Rows(RowIndex)("Total"))
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim InvoiceID As String = txtInvoiceID.Text
Dim ClientID As String = txtClientID.Text
Dim EmployeeID As String = (txtEmployeeID.Text)
Dim FillInDate As Date = CDate(txtFillInDate.Text)
Dim TransportFee As Integer = CInt(txtTransportFee.Text)
Dim EquipmentFee As Integer = CInt(txtEquipmentFee.Text)
Dim LabourFee As Integer = CInt(txtLabourFee.Text)
Dim Total As Integer = CInt(txtTotal.Text)
If CStr(dt.Rows(RowIndex)("paymentmethod")) = "Card" Then
radCard.Select()
ElseIf CStr(dt.Rows(RowIndex)("paymentmethod")) = "Cash" Then
radCash.Select()
Else
radCredit.Select()
End If
Dim sqlQuery As String = ("Exec Insert_Invoice #InvoiceID = ' " & InvoiceID & " ', #ClientID = '" & ClientID & "',#EmployeeID ='" & EmployeeID & "', #FillInDate ='" & FillInDate & "',#TransportFee='" & TransportFee & "',#EquipmentFee = '" & EquipmentFee & "',#LabourFee= '" & LabourFee & "',#Total= '" & Total)
Dim sqlcmnd As New SqlCommand(sqlQuery, sqlConn)
Try
sqlConn.Open()
Dim changes As Integer = sqlcmnd.ExecuteNonQuery()
sqlConn.Close()
MessageBox.Show(changes & "Changes Made")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Save()
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
dt.Rows(RowIndex)("InvoiceID") = CStr(txtInvoiceID.Text)
dt.Rows(RowIndex)("ClientID") = CStr(txtClientID.Text)
dt.Rows(RowIndex)("EmployeeID") = CStr(txtEmployeeID.Text)
dt.Rows(RowIndex)("FillInDate") = CStr(txtFillInDate.Text)
dt.Rows(RowIndex)("TransportFee") = CStr(txtTransportFee.Text)
dt.Rows(RowIndex)("EquipmentFee") = CStr(txtEquipmentFee.Text)
dt.Rows(RowIndex)("LabourFee") = CStr(txtLabourFee.Text)
dt.Rows(RowIndex)("Total") = CStr(txtTotal.Text)
Dim sqlquery As String = "exec edit_invoice '" & txtInvoiceID.Text & "', " & txtLabourFee.Text & ", " & txtTransportFee.Text & ", " & txtEquipmentFee.Text & ", '" & txtpaymentMethod.Text & "', '" & txtClientID.Text & "', '" & txtEmployeeID.Text & "', '" & txtFillInDate.Text & "', '" & txtTotal.Text & "'"
Dim sqlcmnd As New SqlCommand(sqlquery, sqlConn)
Try
sqlConn.Open()
Dim changes As Integer = sqlcmnd.ExecuteNonQuery()
sqlConn.Close()
MessageBox.Show(changes & "Changes Made")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Save()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtInvoiceID.Clear()
txtClientID.Clear()
txtEmployeeID.Clear()
txtFillInDate.Clear()
txtTransportFee.Clear()
txtEquipmentFee.Clear()
txtLabourFee.Clear()
txtTotal.Clear()
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If RowIndex <> MaxRows - 1 Then
RowIndex += 1
InvoiceDetails()
End If
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
RowIndex = MaxRows - 1
InvoiceDetails()
End Sub
Private Sub btnMainMenu_Click(sender As Object, e As EventArgs) Handles btnMainMenu.Click
SecretaryMainMenu.Show()
Me.Hide()
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim invoiceID As String = txtInvoiceID.Text
Dim SqlQuery As String = ("EXECUTE Delete_Invoice #InvoiceID = '" & InvoiceID & "'")
Dim cmd As New SqlCommand(SqlQuery, sqlConn)
Try
sqlConn.Open()
Dim changes As Integer = cmd.ExecuteNonQuery()
sqlConn.Close()
MessageBox.Show(changes & "Record Deleted")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Save()
dt.Rows(RowIndex).Delete()
End Sub
Sub Save()
Dim dataAdapter As New SqlDataAdapter(sqlstr, sqlConn)
Dim commandbuilder As New SqlCommandBuilder(dataAdapter)
dataAdapter.Update(dt)
dataAdapter.Dispose()
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
Dim searchitem As String = InputBox("Input Search invoice ID: ", "Search by ID")
Dim sresult As Boolean = False
searchitem = searchitem.Trim.ToUpper
For i As Integer = 0 To MaxRows - 1
If CStr(dt.Rows(i)("invoiceid")).ToUpper = searchitem Then
sresult = True
RowIndex = i
InvoiceDetails()
End If
Next
If sresult = False Then
MsgBox("No result found", MsgBoxStyle.OkOnly, "Information")
End If
End Sub
Private Sub txtinvoice_validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtInvoiceID.Validating
If Not txtInvoiceID.Text Like "I###" Then
e.Cancel = True
ErrorProvider1.SetError(txtInvoiceID, "Improper ID format")
End If
End Sub
Private Sub txtinvoice_validated(ByVal sender As Object, ByVal e As EventArgs) Handles txtInvoiceID.Validated
ErrorProvider1.SetError(txtInvoiceID, "")
End Sub
End Class
Now I want to call the stored procedure into the textbox Total, which will compute the 'transportFee, EquipmentFee and Labourfee' costs, and display the total into the textbox of txtTotal.Text
How do I write that piece of code?
use executescalar: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
remember to set the commandtype property of the command to stored procedure

Index out of bounds of the array vb.net

I am getting an error at this line:
CheckedListBox3.Items.Remove(CheckedListBox3.CheckedItems(0))
I don't understand why because it does read the first two but not the third... the index of my checkedlistbox1, 2 and 3 is 3 so that makes it (0), (1), and (2) in each while...
Please help me out and tell me where i am wrong because i don't understand how it's possible that he can find the index of the first and second listbox but can't find the index of the third listbox
This is my code:
cmd = New SqlCommand("SELECT serienaam, ouderdom, aantal FROM klantserie Where klantnummer = '" & klantnummer & "' ", con)
Dim ttr As SqlDataReader = cmd.ExecuteReader()
While ttr.Read = True
CheckedListBox1.Items.Add(ttr.Item("serienaam")) "serienaam" = a-map or c-map
CheckedListBox2.Items.Add(ttr.Item("ouderdom")) "ouderdom" = week1 - week16
CheckedListBox3.Items.Add(ttr.Item("aantal")) "aantal" = 1 - 10
End While
added the code that adds the items to the checkedlistbox
Private Sub Button79_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button79.Click
While CheckedListBox1.CheckedItems.Count - 1 >= 0 ''i have changed this line a few times don't really know if it matters to the outcome of the error''
Dim serienaam
Dim oud
Dim aantal As Integer
Dim bedrag As Decimal
Dim totaal As Decimal
Try
serienaam = CheckedListBox1.CheckedItems(0)
oud = CheckedListBox2.CheckedItems(0)
aantal = CheckedListBox3.CheckedItems(0)
Catch ex As Exception
End Try
cmd = New SqlCommand("SELECT " & oud & " FROM series Where naamserie = '" & serienaam & "' ", con)
Dim sdr As SqlDataReader = cmd.ExecuteReader()
If sdr.Read = True Then
Dim week = sdr.Item(oud)
bedrag = week * aantal
totaal = Label69.Text
totaal = totaal - bedrag
sdr.Close()
Label69.Text = totaal
End If
CheckedListBox1.Items.Remove(CheckedListBox1.CheckedItems(0))
CheckedListBox2.Items.Remove(CheckedListBox2.CheckedItems(0))
Try
CheckedListBox3.Items.Remove(CheckedListBox3.CheckedItems(0)) ''<<<----error
this try doesn't do anything actually except for the fact that im not getting any errors anymore
Catch ex As Exception
If ex IsNot Nothing Then
Dim s = CheckedListBox3.Items.Count
CheckedListBox3.SelectedItem = s
CheckedListBox3.Items.Remove(s)
End If
End Try
End While
End Sub
this is the code for the check
Private Sub CheckedListBox1_ItemCheck(ByVal sender As Object, ByVal e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
Dim index As Integer = e.Index
CheckedListBox2.SetItemChecked(index, e.NewValue)
CheckedListBox3.SetItemChecked(index, e.NewValue)
End Sub
my solution since it didn't work.
Private Sub Button76_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button76.Click
Dim serienaam
Dim oud
Dim aantal As Integer
Dim bedrag As Decimal
Dim totaal As Decimal
Dim t As String
serienaam = ComboBox6.SelectedItem
oud = ComboBox7.SelectedItem
aantal = TextBox45.Text
cmd = New SqlCommand("SELECT " & oud & " FROM series Where naamserie = '" & serienaam & "' ", con)
Dim sdr As SqlDataReader = cmd.ExecuteReader()
If sdr.Read = True Then
Dim week = sdr.Item(oud)
bedrag = week
totaal = Label69.Text
totaal = totaal + bedrag * aantal
sdr.Close()
Label69.Text = totaal
t = " '" & serienaam & "' '" & oud & "' '" & aantal & "' "
CheckedListBox1.Items.Add(t)
End If
End Sub
Private Sub Button79_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button79.Click
While CheckedListBox1.CheckedItems.Count <> 0
Dim klantnr As String
Dim serienaam As String
Dim oud As String
Dim list As String
Dim aantal As Integer
Dim bedrag As Decimal
Dim totaal As Decimal
klantnr = TextBox32.Text
list = CheckedListBox1.CheckedItems(0)
Dim strlist = list.Split("'")
For count = 0 To strlist.Length - 1
serienaam = strlist(1)
oud = strlist(3)
aantal = strlist(5)
Next
cmd = New SqlCommand("SELECT " & oud & " FROM series Where naamserie = '" & serienaam & "' ", con)
Dim sdr As SqlDataReader = cmd.ExecuteReader()
If sdr.Read = True Then
Dim week = sdr.Item(oud)
bedrag = week * aantal
totaal = Label69.Text
totaal = totaal - bedrag
sdr.Close()
Label69.Text = totaal
End If
cmd = New SqlCommand("DELETE FROM klantserie Where klantnummer = '" & klantnr & "' And serienaam = '" & serienaam & "' And ouderdom = '" & oud & "' And aantal = '" & aantal & "' ", con)
If con.State = ConnectionState.Closed Then con.Open()
cmd.ExecuteNonQuery()
ShowData()
CheckedListBox1.Items.Remove(CheckedListBox1.CheckedItems(0))
End While
End Sub
Not sure if you've fixed this but I tried to reproduce the problem and failed. Here's what I used:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CheckedListBox1.Items.Clear()
CheckedListBox1.Items.Add("List1Item1")
CheckedListBox1.Items.Add("List1Item2")
CheckedListBox1.Items.Add("List1Item3")
CheckedListBox2.Items.Clear()
CheckedListBox2.Items.Add("List2Item1")
CheckedListBox2.Items.Add("List2Item2")
CheckedListBox2.Items.Add("List2Item3")
CheckedListBox3.Items.Clear()
CheckedListBox3.Items.Add("List3Item1")
CheckedListBox3.Items.Add("List3Item2")
CheckedListBox3.Items.Add("List3Item3")
End Sub
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
Dim index As Integer = e.Index
CheckedListBox2.SetItemChecked(index, e.NewValue)
CheckedListBox3.SetItemChecked(index, e.NewValue)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
While CheckedListBox1.CheckedItems.Count <> 0
Dim serienaam As String
Dim oud As String
Dim aantal As String
serienaam = CheckedListBox1.CheckedItems(0)
oud = CheckedListBox2.CheckedItems(0)
aantal = CheckedListBox3.CheckedItems(0)
CheckedListBox1.Items.Remove(CheckedListBox1.CheckedItems(0))
CheckedListBox2.Items.Remove(CheckedListBox2.CheckedItems(0))
CheckedListBox3.Items.Remove(CheckedListBox3.CheckedItems(0))
End While
End Sub
This works just fine. I can add items to the boxes using Button 1 and then check anything in the first box (which checks the corresponding items in the other boxes based on index - couldn't be bothered to wire up lists 2 and 3 to do the same) and then I can delete the checked items with no errors using Button2. The only change to yours is obviously I'm using mocked data, not SQL queries.

How to fill up the AutoCompleteCustomSource

How to fill up the AutoCompleteCustomSource List with the query results using Data reader in vb.net ?
An example code needed.
Edit 1:
This is what I have tried and its not working
Private Sub cbEmployeeNo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbEmployeeNo.Click
cbEmployeeNo.AutoCompleteCustomSource.Clear()
Dim mySelectQuery As String = "SELECT * FROM EmployeeTable WHERE " & cbSearch.Text & " LIKE '" & cbEmployeeNo.Text & "' AND Status LIKE '" & cbStatus.Text & "'"
Dim myConnString As String = "Data Source=" & Application.StartupPath & "\Database\SimpleDB.db3"
Dim sqConnection As New SQLiteConnection(myConnString)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
sqConnection.Open()
Try
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
Dim m As Integer
Do While sqReader.Read
For m = 1 To sqReader.FieldCount() - 1
If (Not sqReader.IsDBNull(m)) Then
If cbSearch.Text = "EmployeeID" Then
cbEmployeeNo.AutoCompleteCustomSource.Add(sqReader.GetInt32(m))
Else
cbEmployeeNo.AutoCompleteCustomSource.Add(sqReader.GetString(m))
End If
End If
Next m
Loop
sqReader.Close()
Catch ex As Exception
MsgBox("Error: " & ex.ToString, vbExclamation)
Finally
sqConnection.Close()
End Try
End Sub
Edit 2: This is the second code I tried (following the link in DevExpress's answer). Its not working either
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sStringColl As New AutoCompleteStringCollection
Dim mySelectQuery As String = "SELECT * FROM EmployeeTable WHERE " & cbSearch.Text & " LIKE '" & cbEmployeeNo.Text & "' AND Status LIKE '" & cbStatus.Text & "'"
Dim myConnString As String = "Data Source=" & Application.StartupPath & "\Database\SimpleDB.db3"
Dim sqConnection As New SQLiteConnection(myConnString)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
sqConnection.Open()
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
While sqReader.Read()
sStringColl.AddRange(New String() {sqReader(0)})
End While
cbEmployeeNo.AutoCompleteCustomSource = sStringColl
End Sub
I have found the code you are looking for at:
AutoCompleteCustomSource