Add value to textbox after clicking the "Add" button in VB.net - vb.net

Here is my Part of the coding...what i want is when i clicked the button, the value from the database will be added into the textbox. But what i get when i click the button, the value in the textbox is straight replaced by the new value from the database.
anybody can help me on solving this problem?
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
txtShowDescrip.Text &= cmbDescrip.SelectedItem & ","
Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=SDP_DB.accdb")
Dim str As String
Dim dr As OleDbDataReader
Dim cmd As OleDbCommand
Dim total As Integer = 0
conn.Open()
str = "Select * From ChargeTable Where Description='" & cmbDescrip.Text & "'"
cmd = New OleDbCommand(str, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows = True Then
total += dr.Item("PriceRate")
txtShowRate.Text = "$" & total
End If
dr.Close()
conn.Close()
End Sub

Omg, read your own post back;
... when i clicked the button, the value in the textbox will be added into the textbox.
But when i click the button, the value in the textbox is straight replaced by the new value.
So what exactly do you want to happen the the button is clicked?

Your currently set the text of the textbox to the new value, if you want to add new stuff you need to use & or &=
Dim nfi As New System.Globalization.NumberFormatInfo()
nfi.CurrencySymbol = "$"
dim tot as decimal = total + Decimal.Parse(TextBox1.Text, Globalization.NumberStyles.Any, nfi)
txtShowRate.Text = "$" & tot

You may use static declaration ..
Static total As Integer = 0
Or if you still use Dim ..
If dr.HasRows = True Then
total = val(txtShowRate.Text) + dr.Item("PriceRate")
txtShowRate.Text = "$" & format(total)
End If

If dr.HasRows = True Then
total = CType(txtShowRate.Text,Integer) + dr.Item("PriceRate")
txtShowRate.Text = "$" & total.ToString
End If

Related

Update edited ComboBox items in database instead of adding them

I have a combobox named "Barcode", I fill it from database like this:
Sub fillIBarcode()
Barcode.DataSource = Nothing
Barcode.Items.Clear()
Dim adp As New SqlClient.SqlDataAdapter("Select distinct Barcode from Items where ItemCode=N'" & (ItemsDGV.CurrentRow.Cells(0).Value) & "'", SQlconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
'=====================================================
For I = 0 To dt.Rows.Count - 1
Barcode.Items.Add(dt.Rows(I).Item("Barcode"))
Barcode.SelectedIndex = 0
Next
End Sub
And it displays like that:
When the user edits and changes any numbers in the combobox and clicks the "Edit" button, how to submit this change and update the combobox items list immediately in the database?
I tried:
Private Sub Editbtn_Click(sender As Object, e As EventArgs) Handles Editbtn.Click
Dim cmdd As New SqlClient.SqlCommand
cmdd.Connection = SQlconn
cmdd.CommandText = "delete from Items where ItemCode=N'" & (ItemCode.Text) & "'"
cmdd.ExecuteNonQuery()
Dim sql = "select * From Items where ItemCode=N'" & (ItemCode.Text) & "'"
Dim adp As New SqlClient.SqlDataAdapter(sql, SQlconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
If dt.Rows.Count = 0 Then
For i = 0 To Barcode.Items.Count - 1
Dim dr = dt.NewRow
dr!ItemCode = ItemCode.Text
dr!Barcode = Barcode.Items(i).ToString
dt.Rows.Add(dr)
Next
Dim cmd As New SqlClient.SqlCommandBuilder(adp)
adp.Update(dt)
End If
End Sub
But it adds the new value, instead of updating the existing one.
I mean it added three barcodes, the original two, and the new edited one.
use SQL UPDATE QUERY :
you must conserve dt across form event to keep old value
dt has same index as combobox
declare dt as global in front of form code
Dim dt as datatable
in Sub fillIBarcode() remove DIM
dt = ds.Tables(0)
and in event handler execute an UPDATE query with ref to combobox selectedIndex:
Private Sub Editbtn_Click(sender As Object, e As EventArgs) Handles Editbtn.Click
Dim cmdd As New SqlClient.SqlCommand
cmdd.Connection = SQlconn
cmdd.CommandText = "UPDATE Items SET ItemCode=N'" & (ItemCode.Text) & "' WHERE ItemCode = N'" & dt.rows(Barcode.SelectedIndex).Item("Barcode") & "'"
cmdd.ExecuteNonQuery()
'update dt
dt.rows(Barcode.SelectedIndex).Item("Barcode") = ItemCode.Text
End Sub

DataGridView is not displaying my delete button

I have a problem in my 2nd load of data using a DataGridView.
Here is my DataGridView and has a delete button when the data is first loaded:
On my 2nd load of data, this is the error I get:
After I click Ok, this is what happens in my DataGridView:
The delete button is gone.
This is my code:
Private Sub loaddata()
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
con.ConnectionString = "server=192.168.1.10;database=orderingsystem;username=server;password=server"
Dim da As New MySqlDataAdapter
Dim ds As New DataTable
Dim source As New BindingSource
Try
con.Open()
Dim query As String
Dim total As Double
Dim btn As New DataGridViewButtonColumn
btn.HeaderText = "Action"
btn.Text = "Delete"
btn.Name = "btn"
btn.UseColumnTextForButtonValue = True
query = "SELECT prodID, SUM(prodQty) as QTY, prodname as Name, prodPrice*SUM(prodQty) as Total from orderedlist where table_name = '" & Form1.Table_1.Name & "' GROUP BY prodID"
cmd = New MySqlCommand(query, con)
da.SelectCommand = cmd
da.Fill(ds)
source.DataSource = ds
dgv_myOrder.DataSource = ds
dgv_myOrder.Columns(0).Visible = False
For i As Integer = 0 To dgv_myOrder.Rows.Count - 1
total += Convert.ToDecimal(dgv_myOrder.Rows(i).Cells(3).Value).ToString("0.00")
Next
dgv_myOrder.Columns.Add(btn)
lbl_Total.Text = Decimal.Parse(total).ToString("0.00")
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Private Sub dgv_myOrder_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv_myOrder.CellClick
If e.RowIndex = dgv_myOrder.NewRowIndex Or e.RowIndex < 0 Then
ElseIf e.ColumnIndex = dgv_myOrder.Columns("btn").Index Then
Dim connection As String = "server=192.168.1.10;database=orderingsystem;username=server;password=server;"
Dim con2 As New MySqlConnection(connection)
con2.Open()
Dim data As String = dgv_myOrder.SelectedRows(0).Cells(0).Value.ToString
Label2.Text = data
Dim rd2 As MySqlDataReader
Dim cmd2 As New MySqlCommand("UPDATE orderedlist SET cancelstatus = 1 WHERE prodID = '" & Label2.Text & "' and table_name = '" & Form1.Table_1.Name & "'", con2)
rd2 = cmd2.ExecuteReader
con2.Close()
con2.Open()
Dim rd3 As MySqlDataReader
Dim cmd3 As New MySqlCommand("UPDATE tableassistance SET cancellation = 1 WHERE table_name = '" & Form1.Table_1.Name & "'", con2)
rd3 = cmd3.ExecuteReader
MessageBox.Show("Wait for confirmation!", "System")
Me.Close()
Label2.Text = ""
End If
End Sub
I call loaddata() in my form load.
First remove this Line:
dgv_myOrder.Columns.Add(btn)
Don't add the button to datagridview inside code create it form the designer and use binding for other columns.
Steps :
1 . Create all your datagrdiview columns , using add columns button in the top right of the datagridview
this is how you add columns
2 .after you add the columns , bind every column to its related Column in database like this , you can get this window when you click on EditColumns in datagidview designer , change the DataPropertyName in the properties of each column change it to the name of the datatable column name that you want it to preview but not add it to the delete column button:
Binding the columns
3 . go to the properties of your delete button column in the datagridview you will find property called DefalutCellStyle inside it will find NullValue change it to "Delete".
Change the null value

simple login form error VB 2010

I've search a lot of resources and couldn't fix it.
My problem is when I click the button event the next form doesn't show and also I want to close my login form at the same time.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim firstname As String = ""
Dim lastname As String = ""
Dim ara As Boolean = False
cn = New OleDbConnection(con)
cn.Open()
Dim user As String
Dim pass As String
user = TextBox1.Text
pass = TextBox2.Text
With cmd
.Connection = cn
.CommandText = "Select * from users WHERE username='" & user & "' AND password='" & pass & "'"
.ExecuteNonQuery()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
ara = True
While rdr.Read()
firstname = rdr("firstname").ToString
lastname = rdr("lastname").ToString
lib_name = firstname + lastname
End While
If ara = True Then
Form2.Show()
Me.Close()
x = True
Else
MsgBox(" Access Denied!" + Environment.NewLine + "Sorry, username or password is incorrect!")
End If
End If
End With
cn.Close()
cmd.Dispose()
1 : You are opening the gates of SQL INJECTION. Read more . Instead of passing values directly in your query, pass parameters first and use them later(For unknown reason, the code formatting is not working below) :
Dim cmd as New OleDbCommand("Select * from users WHERE username=#user AND password=#pass" , con)
With cmd
.Parameters.Add("#user", OleDbType.Varchar).Value = user
.Parameters.Add("#user", OleDbType.Varchar).Value = password
End With
2 : Your If statement will only work IDateReader.HasRows returns true and if ara=True which is unnecessary. .HasRows is a boolean, you don't need to create another boolean and pass the value to it. However, the rest of your code will only execute if your conditions match
3 : Form1.Close and AnotherForm.Show will never work if in your Project Proerties , Shutdown Mode is set to On main window close(by default). Either change it to On Explicit window close or On last window close or change
Me.CLose To
Me.Hide
4 : In order to reduce too much code , you can use Using Statement :
Using cmd as New SqlCommand("Select * from users WHERE username=#user AND password=#pass" , con)
'''codes here
End Using
''Now no need to call cmd.Dispose
Hope this helps :)

VB.NET RowUpdating event doesn't work

The following code runs successfully with no errors, but I still don't get the new data from the grid, by adding a break point, and stepping forward, the data in the variables are the original data, not the updated data, what am I missing?
Private Sub grvSample_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles grvSample.RowUpdating
Dim row As GridViewRow = DirectCast(grvSample.Rows(e.RowIndex), GridViewRow)
Dim passportNumber As TextBox = DirectCast(row.FindControl("txtNumber"), TextBox)
Dim expiry As TextBox = DirectCast(row.FindControl("txtExpiry"), TextBox)
Dim type As TextBox = DirectCast(row.FindControl("txtType"), TextBox)
Dim name As TextBox = DirectCast(row.FindControl("txtName"), TextBox)
Dim cinvnum As TextBox = DirectCast(row.FindControl("txtCINVNUM"), TextBox)
Dim last As TextBox = DirectCast(row.FindControl("txtLast"), TextBox)
Dim drplist As DropDownList = DirectCast(row.FindControl("DDLNat"), DropDownList)
Dim Conn As New SqlConnection("Data Source=ADMIN-PC;Initial Catalog=T1INV;Integrated Security=True")
Dim cmd As New SqlCommand("update pass_details set passnat='" & drplist.SelectedValue & "', passno='" & passportNumber.Text.Trim() & "', passexp='" & expiry.Text.Trim() & "', passtype='" & type.Text.Trim() & "', nameonpass='" & name.Text.Trim() & "', namelast='" & last.Text.Trim & "' where cinvnum='" & cinvnum.Text.Trim() & "'", Conn) ' where cinvnum='" & grvSample.Rows(e.RowIndex) & "'")
Try
Conn.Open()
cmd.ExecuteNonQuery()
' Refresh the data
grvSample.EditIndex = -1
Dim SSQL = "select * from pass_details"
Dim ds As New DataSet("GET_HIS")
Dim adp As New SqlDataAdapter(SSQL, Conn)
adp.Fill(ds, "TAB_SMT")
grvSample.DataSource = ds.Tables("TAB_SMT")
grvSample.DataBind()
Catch ee As SqlException
Finally
cmd.Dispose()
Conn.Close()
Conn.Dispose()
End Try
End Sub
I assume that you're databinding the GridView also on postbacks. That would override the changed values.
So check it in Page_Load in the following way:
If Not Page.IsPostBack Then
BindGrid()
End If
Apart from that GridViewUpdateEventArgs contains a dictionary with NewNalues.
Dim passportNumber = e.NewValues("passno")
Note that they're also overridden on databind.

Update a Single cell of a database table in VB.net

I am using MS Access Database. Now I have to update a particular cell value. Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim Presc As New System.Text.StringBuilder
Dim prs As String(), j As Integer
prs = Split(txtPrescription.Text, vbCrLf)
For j = 0 To prs.Length - 1
Presc.Append(prs(j))
Presc.Append(",")
Next
Try
str = Trim(lsvCase.SelectedItems(0).Text)
'MessageBox.Show(str)
Dim con As System.Data.OleDb.OleDbConnection
Dim ds As New DataSet
Dim rea As System.Data.OleDb.OleDbDataReader
con = New OleDb.OleDbConnection
Dim da As New System.Data.OleDb.OleDbDataAdapter
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source= F:\Sowmya Laptop Backups\sowdb1.accdb;"
con.Open()
Dim cmd As OleDb.OleDbCommand = con.CreateCommand
cmd.CommandText = "UPDATE Casehistory set Prescription =' " & Presc.ToString() & "'"
rea = cmd.ExecuteReader
cmd.ExecuteNonQuery()
da.FillSchema(ds, SchemaType.Mapped)
da.Update(ds, "Casehistory")
con.Close()
Catch ex As Exception
Finally
End Try
End Sub
This code updates all the cells in that column. I want to update only the particular cell having Case_ID = str
Where I have to add the WHERE clause (WHERE Case_ID = " & str & "
I would use command parameters, neater and prevents the SQL injection issue. Something like:
cmd.CommandText = "UPDATE Casehistory set Prescription =#Presc WHERE Case_ID = #CaseID"
cmd.Parameters.AddWithValue("#Presc", Presc.ToString())
cmd.Parameters.AddWithValue("#CaseID",str)
As an aside, having all this code in the button click event is less than ideal. You might want to investigate structuring your app in a more maintainable way - perhaps with a Data Layer for example.
The Where clause should be appended to the end of the OleDbCommmand.CommandText, where you define the Update statement.