VB.NET RowUpdating event doesn't work - vb.net

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.

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

Input array is longer than the number of columns

In the event dragdrop of a datagridview I got this error:
Here's the whole code of my dragdrop event :
Private Sub DataGridView1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
Dim clientPoint As Point = DataGridView1.PointToClient(New Point(e.X, e.Y))
Dim hit As DataGridView.HitTestInfo = DataGridView1.HitTest(clientPoint.X, clientPoint.Y)
Dim dgvr As DataGridViewRow = DirectCast(e.Data.GetData(GetType(DataGridViewRow)), DataGridViewRow)
Dim celldata As Object() = New Object(dgvr.Cells.Count) {}
For col As Integer = 0 To dgvr.Cells.Count - 1
celldata(col) = dgvr.Cells(col).Value
Next
Dim dt As New DataTable()
dt = ds_data.Tables(0)
Dim colCheckbox As DataColumn = dt.Columns.Add("Column1", GetType(Boolean))
Dim row As DataRow = dt.NewRow()
row.ItemArray = celldata
dt.Rows.InsertAt(row, hit.RowIndex)
dgvr.DataGridView.Rows.Remove(dgvr)
Dim sqlCmd As SqlCommand
sqlCmd = con.CreateCommand()
sqlCmd.CommandText = "update megatom_data_commande set ordre='" & hit.RowIndex & "' where id='" & DataGridView1.Rows(hit.RowIndex).Cells("ID").Value.ToString & "'"
Try
sqlCmd.ExecuteNonQuery()
DataGridView2.DataSource = ds_data2.Tables(0).DefaultView
DataGridView1.DataSource = ds_data.Tables(0).DefaultView
Dim CMD As New SqlCommand("PLANNIFIER")
CMD.Parameters.Add("#CHAINE", SqlDbType.VarChar).Value = cboChaine.SelectedItem.ToString
ExecuteCMD(CMD)
Catch ex As SqlException
End Try
End Sub
In fact my datatable have 15 columns but I added manually a checkbox column to select rows so I think i have a problem of indexes but I dont know how to resolve that problem.
My ds_data is defined like the code below:
requestPlanifie = "select megatom_data_commande.id as ID,numéro,observation,moule,commande,id_etat,programme,ordre,moule,glav,Qté_commandée_Totale," _
& " Qté_coupée_cuir, Qté_coupée_synthétique, Qté_piquée, Qté_finie from megatom_data_commande" _
& " inner join dbo.MEGATOM_DATA_MOULE on megatom_data_moule.id=megatom_data_commande.id_moule " _
& " where id_chaine='" & cboChaine.Text & "' and ( id_etat='3' or id_etat='4') order by numéro asc,ordre asc"
Dim dataAdapter As New SqlDataAdapter(requestPlanifie, con)
Try
dataAdapter.Fill(ds_data, "ds_data")
dataAdapter2.Fill(ds_data2, "ds_data2")
Catch ex As SqlException
End Try
DataGridView1.DataSource = ds_data.Tables(0).DefaultView

Retrieve data from database according to multiple checked items from CheckedListBox

How to retrieve data from database according to multiple checked items from CheckedListBox? PlEASE GUIDE ME!!!
I'm currently doing a tutorial regarding to retrieve data from table according to multiple checked items from a CheckedListBox. Right now i'm able to retrieve data from table by only 1 checked item. how to make it retrievable by multiples checked item?
checklistbox1
checklistbox2
The tutorial will be: first load all related data into checklistbox1 as item, and user(s) may go and check the listed item, once the user checked particulars item(s) checklistbox2 will now query out data from another table where [field] = checked item(s) from checklistbox1.
load event as class
Public Sub Startload()
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & aaa & "';Persist Security Info=False;")
Dim dt1 As New DataTable
Dim sqlstr As String = "SELECT * FROM tbl"
Dim command As New OleDbCommand(sqlstr, connection)
Dim adpt As New OleDbDataAdapter(command)
adpt.SelectCommand = command
adpt.Fill(dt1)
CheckedListBox1.DisplayMember = "name"
CheckedListBox1.ValueMember = "ID"
CheckedListBox1.DataSource = dt1
End Sub
when Checked change execute checkedload()
Private Sub CheckedListBox1_ItemCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
Label1.Text = CheckedListBox1.SelectedValue
checkedload()
End Sub
After checked items from checklistbox1 (checkedload) will execute and retrieves data and show in checklistbox2
Private Sub checkedload()
Dim x As String = Label1.Text
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & aaa & "';Persist Security Info=False;")
Dim dt2 As New DataTable
Dim sqlstr2 As String = "SELECT * FROM tbl2 WHERE [name]='" & x & "'"
Dim command2 As New OleDbCommand(sqlstr2, connection)
Dim adpt2 As New OleDbDataAdapter(command2)
adpt2.SelectCommand = command2
adpt2.Fill(dt2)
CheckedListBox2.DisplayMember = "namex"
CheckedListBox2.ValueMember = "ID"
CheckedListBox2.DataSource = dt2
End Sub
Self Solved
Dim i As Integer
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & aaa & "';Persist Security Info=False;")
Dim dt2 As New DataTable
For i = 0 To CheckedListBox1.Items.Count - 1 Step i + 1
If CheckedListBox1.GetItemCheckState(i) = CheckState.Checked Then
Dim xx As String = (CType(CheckedListBox1.Items(i), DataRowView))("name")
Dim sqlstr2 As String = "SELECT * FROM tbl2 WHERE [name]='" & xx & "'"
Dim command2 As New OleDbCommand(sqlstr2, connection)
Dim adpt2 As New OleDbDataAdapter(command2)
adpt2.SelectCommand = command2
adpt2.Fill(dt2)
CheckedListBox2.DisplayMember = "namex"
CheckedListBox2.ValueMember = "ID"
CheckedListBox2.DataSource = dt2
End If
Next
Private Sub CheckedListBox1_ItemCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
Dim i as Integer=0
For Each li as ListItem in CheckedListBox1.Items
If li.Selected=True Then
Dim lab As New Label
lab.ID="lab" & i
lab.Text=li.SelectedItem.Value
i += 1
End If
Next
hiddenfield1.Value=i 'hidden field
checkedload()
End Sub
Private Sub checkedload()
For i as Integer = o To hiddenField1.Value
Dim x As String = Request.Form("lab" & i)
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & aaa & "';Persist Security Info=False;")
Dim dt2 As New DataTable
Dim sqlstr2 As String = "SELECT * FROM tbl2 WHERE [name]='" & x & "'"
Dim command2 As New OleDbCommand(sqlstr2, connection)
Dim adpt2 As New OleDbDataAdapter(command2)
adpt2.SelectCommand = command2
adpt2.Fill(dt2)
CheckedListBox2.DisplayMember = "namex"
CheckedListBox2.ValueMember = "ID"
CheckedListBox2.DataSource = dt2
Next
End Sub
I haven't checked it anyway. but it could help you

Add value to textbox after clicking the "Add" button in 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

SELECT statement with JOIN and WHERE clause not returning any data

I have problem with data that needs to be seen on datagridview. Bellow is my code:
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim CONNECT_STRING As String = (...)
Dim cnn As New OleDbConnection(CONNECT_STRING)
cnn.Open()
MsgBox(status_narocila.value)
Dim sql As String = "SELECT artikel.st_artikla, artikel.naziv_artikla, narocilo.kolicina, narocilo.barva_tiska, narocilo.izvedba, narocilo.opombe, narocilo.datum_narocila, narocilo.rok_izdelave, narocilo.status, narocilo.ID FROM (narocilo INNER JOIN artikel ON narocilo.id_artkla = artikel.ID) WHERE(narocilo.ID = '" & status_narocila.value & "')"
Dim cmd As New OleDbCommand(sql, cnn)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds, "artikel")
cnn.Close()
DataGridView1.DataSource = ds.Tables("artikel")
End Sub
End Class
Value status.narocila.value is integer, I've tested it and getting right value from it. The code is working fine without WHERE clause.
= '" & status_narocila.value & "')"
should be
= " & status_narocila.value & ")"
no ' on numeric data types.
If narocilo.ID is also an integer, then the problem is you're using text qualifers on an integer field.
Try changing your WHERE clause to:
WHERE(narocilo.ID = " & status_narocila.value & ")"