VB.NET - Deleted row information cannot be accessed through the row - vb.net

This is my Delete button code. When I click on the Delete button, it displays the error message "Deleted row information cannot be accessed through the row." So, what will be the possible solution?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If (i < ds.Tables(0).Rows.Count - 1) Then
Dim r1 As DataRow
'r1 = ds.Tables(0).NewRow(i)(0)
'r1.Delete()
'Me.da.Update(ds.Tables(0))
ds.Tables(0).Rows(i).Delete()
ds.Tables(0).GetChanges(DataRowState.Deleted)
'ds.Tables(0).AcceptChanges()
'ds.AcceptChanges()
'Me.da.Update(Me.ds.Tables(0).Rows(i)("cust_id")).ToString()
'Me.da.Update(Me.ds.Tables(0).Rows(i)("cust_id"))
Me.da.Update(Me.ds.Tables(0).Rows(i).Item(0))
' Me.da.Update(Me.ds.Tables(0))
' ds.Tables(0).AcceptChanges()
i = i + 1
TextBox1.Text = ds.Tables(0).Rows(i)("cust_id").ToString()
TextBox2.Text = ds.Tables(0).Rows(i)("fname").ToString()
TextBox3.Text = ds.Tables(0).Rows(i)("sname").ToString()
TextBox4.Text = ds.Tables(0).Rows(i)("lname").ToString()
TextBox5.Text = ds.Tables(0).Rows(i)("address").ToString()
TextBox6.Text = ds.Tables(0).Rows(i)("city").ToString()
TextBox7.Text = ds.Tables(0).Rows(i)("state").ToString()
TextBox8.Text = ds.Tables(0).Rows(i)("contact1").ToString()
TextBox9.Text = ds.Tables(0).Rows(i)("contact2").ToString()
TextBox10.Text = ds.Tables(0).Rows(i)("email").ToString()
End If
End Sub

You have the data shown in a grid or another control and when you delete it, the information is refreshed on the screen and this is when the control throws the error that the information cannot be accessed.
Before you delete a row in your table, you need to make sure it is removed from any UI elements, like binding sources or grids.

Related

dynamic sql generation error occured when trying to update database

I followed your code and I have put it a msgbox to confirm and yes its returns the right row number. However an error occurred here's my code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cb As New OleDb.OleDbCommandBuilder(da) 'command builder to update the database
ds.Tables("inventory_table").Rows(marker).Item(0) = TextBox1.Text 'update dataset
ds.Tables("inventory_table").Rows(marker).Item(1) = TextBox2.Text 'update dataset
ds.Tables("inventory_table").Rows(marker).Item(2) = TextBox3.Text 'update dataset
ds.Tables("inventory_table").Rows(marker).Item(3) = TextBox4.Text 'update dataset
ds.Tables("inventory_table").Rows(marker).Item(4) = TextBox5.Text 'update dataset
ds.Tables("inventory_table").Rows(marker).Item(5) = TextBox6.Text 'update dataset
ds.Tables("inventory_table").Rows(marker).Item(6) = TextBox7.Text 'update dataset
da.Update(ds, "inventory_table") 'this is where the updating of database takes place
MsgBox("Data updated")
End Sub
Private Sub DataGridView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.DoubleClick
TextBox1.Text = DataGridView1.SelectedRows(0).Cells(0).Value
TextBox2.Text = DataGridView1.SelectedRows(0).Cells(1).Value
TextBox3.Text = DataGridView1.SelectedRows(0).Cells(2).Value
TextBox4.Text = DataGridView1.SelectedRows(0).Cells(3).Value
TextBox5.Text = DataGridView1.SelectedRows(0).Cells(4).Value
TextBox6.Text = DataGridView1.SelectedRows(0).Cells(5).Value
TextBox7.Text = DataGridView1.SelectedRows(0).Cells(6).Value
marker = Me.DataGridView1.SelectedRows(0).Index
MsgBox(marker)
End Sub
The error says:
dynamic sql generation for the updatecommand is not supporyed against
a selectcommand that does not return any key column information
and the line da.update(ds, "inventory_table") is highlighted.
In the double click event set a global variable:
_rowIndex = DataGridView1.SelectedRows(0).Index
Then
ds.Tables("inventory_table").Rows(_rowIndex).Item(1) = TextBox1.Text
ds.Tables("inventory_table").Rows(_rowIndex).Item(2) = TextBox2.Text
ds.Tables("inventory_table").Rows(_rowIndex).Item(3) = TextBox3.Text
ds.Tables("inventory_table").Rows(_rowIndex).Item(4) = TextBox4.Text
ds.Tables("inventory_table").Rows(_rowIndex).Item(5) = TextBox5.Text
ds.Tables("inventory_table").Rows(_rowIndex).Item(6) = TextBox6.Text
ds.Tables("inventory_table").Rows(_rowIndex).Item(7) = TextBox7.Text

How do you change the value in my.settings in a form when you enter numbers in a textbox in VB.Net

I was wondering if you could help me? My question is that, is there a way of changing the value in my.Settings in a form if you enter a number/decimal in a textbox and click a button and then update in the settings to be then changed in another from which is linked to my.Settings in a variable?!
Form 1:
Public Class frmConverter
Dim input As String
Dim result As Decimal
Dim EUR_Rate As Decimal = My.Settings.EUR_Rates
Dim USD_Rate As Decimal = 1.6
Dim JYP_Rate As Decimal = 179.65
Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
input = txtInput.Text
Try
If ComboBox1.Text = "£" Then
Pounds()
ElseIf ComboBox1.Text = "€" Then
Euros()
ElseIf ComboBox1.Text = "$" Then
Dollars()
ElseIf ComboBox1.Text = "¥" Then
Yen()
End If
Catch es As Exception
MsgBox("Error!")
End Try
End Sub
Private Sub btnSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSettings.Click
Me.Hide()
frmExchange.Show()
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
txtInput.Text = ""
lblResult.Text = ""
End Sub
Function Pounds()
If ComboBox1.Text = "£" And ComboBox2.Text = "€" Then
result = (input * EUR_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
ElseIf ComboBox1.Text = "£" And ComboBox2.Text = "$" Then
result = (input * USD_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
ElseIf ComboBox1.Text = "£" And ComboBox2.Text = "¥" Then
result = (input * JYP_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
End If
Return 0
End Function
Form 2:
Public Class frmExchange
Private Sub frmExchange_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
My.Settings.EUR_Rates = (txtinput.Text)
My.Settings.Save()
My.Settings.Reload()
End Sub
Public Sub SetNewRate(ByVal rate As Decimal)
txtinput.Text = rate.ToString
End Sub
Private Sub btnchange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnchange.Click
If ComboBox1.Text = "€" Then
My.Settings.USD_Rates = (txtinput.Text)
frmConverter.SetNewRate(txtinput.Text)
End If
End Sub
End class
It sounds like you are trying to use My.Settings as some sort of set of global reference variables. Thats not what they are for, not how they work and not what they are.
First, turn on Option Strict as it looks like it may be Off. This will store the decimal value of a textbox to a Settings variable which is defined as a Decimal:
My.Settings.USD_Rates = CDec(SomeTextBox.Text)
Thats all it will do. It wont save the value and it wont pass it around or share it with other forms and variables.
My.Settings.Save 'saves current settings to disk for next time
My.Settings.Reload 'Load settings from last time
This is all covered on MSDN. There is no linkage anywhere. If you have code in another form like this:
txtRate.Text = My.Settings.USD_Rates.ToString
txtRate will not automatically update when you post a new value to Settings. There are just values not Objects (see Value Types and Reference Types). To pass the new value to another form:
' in other form:
Public Sub SetNewRate(rate As Decimal)
' use the new value:
soemTextBox.Text = rate.ToString
End Sub
in form which gets the change:
Private Sub btnchangeRate(....
' save to settings which has nothing to do with passing the data
My.Settings.USD_Rates = CDec(RateTextBox.Text)
otherForm.SetNewRate(CDec(RateTextBox.Text))
End Sub
You may run into problems if you are using the default form instance, but that is a different problem.
You botched the instructions. The 2 procedures are supposed to go in 2 different forms - one to SEND the new value, one to RECEIVE the new value. With the edit and more complete picture, there is an easier way.
Private Sub btnSettings_Click(...) Handles btnSettings.Click
' rather than EMULATE a dialog, lets DO a dialog:
'Me.Hide()
'frmExchange.Show()
Using frm As New frmExchange ' the proper way to use a form
frm.ShowDialog
' Im guessing 'result' is the xchg rate var
result = CDec(frm.txtInput.Text)
End Using ' dispose of form, release resources
End Sub
In the other form
Private Sub btnchange_Click(....)
' do the normal stuff with Settings, if needed then:
Me.Hide
End Sub

Added new row to datagrid but the value keeps on the first row

I tried making simple program that add new row in my datagridview when I click a button and send a specific value to new added row. Here's the code
http://pastebin.com/mN5QwL1Z
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button2.Click
Dim baris As Integer
baris = 0
perintah.Connection = koneksi
perintah.CommandType = CommandType.Text
perintah.CommandText = "select * from film where kode_film ='" & TextBox11.Text & "'"
dr = perintah.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
DataGridView1.Rows.Add()
DataGridView1.Rows(baris).Cells(0).Value = dr("kode_film")
DataGridView1.Rows(baris).Cells(1).Value = dr("nama_film")
DataGridView1.Rows(baris).Cells(2).Value = dr("stok")
dr.Close()
End If
dr.Close()
End Sub
The problem is, each time I click the button, it do makes a new row in datagridview, but the value keeps on the first row and not inserted in the new added value.
Have googled so many times but haven't found the answer. Need your hand, guys.
Sorry my bad English.
You're not changing the value of baris anywhere so you always get the row at index 0. The Add method returns the index of the new row so use that. Better still, use the overload of Add that takes the cell values as arguments, so you create and populate the row in a single line of code.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button2.Click
Dim baris As Integer
baris = 0
perintah.Connection = koneksi
perintah.CommandType = CommandType.Text
perintah.CommandText = "select * from film where kode_film ='" & TextBox11.Text & "'"
dr = perintah.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
DataGridView1.Rows.Add()
DataGridView1.Rows(baris).Cells(0).Value = dr("kode_film")
DataGridView1.Rows(baris).Cells(1).Value = dr("nama_film")
DataGridView1.Rows(baris).Cells(2).Value = dr("stok")
dr.Close()
baris = baris + 1
End If
dr.Close()
End Sub
Had changed the value of baris but the value still on the first row and it replaces the previous value I inserted.

nullreferenceexception in gridview when header is clicked

In my DataGridView selectionChange i have this code, so when the row change the texbox also changes. the code below works, i click the row and it displays right, also when i press up/down arrows. My problem is when I click somwhere in the Header of the grid i have this nullreferenceexception error Object reference not set to an instance of an object.. I don't have idea how to handle it, since i down know what it returns.
Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
Dim index As Integer
index = DataGridView1.CurrentCell.RowIndex '<<<<--problem here when I click the header
If (index <= maxrows - 1) Or (index <> Nothing) Then
TextBox2.Text = DataGridView1.Item(1, index).Value()
TextBox3.Text = DataGridView1.Item(2, index).Value()
TextBox4.Text = DataGridView1.Item(3, index).Value()
End If
End Sub
A null reference is raised whenever you get the RowIndex wherein there is no ROW is selected.
Clicking the header calls SORT and this clears the selection.
This will help you get rid of the nullreference exception
If DatagridView1.SelectedRows.Count = 0 Then
Msgbox "Nothing Selected"
Exit Sub 'Trapping
End If
Code:
Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
If DatagridView1.SelectedRows.Count = 0 Then
Msgbox "Nothing Selected"
Exit Sub 'Trapping
End If
Dim index As Integer
With DataGridView
index = .CurrentRow.RowIndex
If (index <= maxrows - 1) Then
TextBox2.Text = .Item(1, index).Value()
TextBox3.Text = .Item(2, index).Value()
TextBox4.Text = .Item(3, index).Value()
End If
End With
End Sub

How do I read contents of a DataTable and assign them to other controls?

Good morning,
I've been up all night trying to figure this out on my own without bugging anybody else, but I can't.
I've been successful in querying my MySQL database and gotten a set of records into a DataTable (dbTable). During debugging, I can see its contents so I know the data is there. Initially, the DataTable is used to populate a ListView control I have on my form.
When I select a record, I want the contents of the DataTable (or the query I just ran) to be assigned to some TextBox controls. I can't seem to figure out how to do this. Any help would be greatly appreciated.
UPDATE TO ADD IMAGES:
I'm hoping these screenshots will give an idea of what I'm looking to do. The first image shows what happens after an account number has been entered. The second box shows a Groupbox expanded to reveal the form fields after a record has been selected in the ListView.
The control names are: TextBoxCustomer, TextBoxLastName, TextBoxFirstName, ComboBoxSalutation, ComboBoxCardType, TextBoxCard.Text, TextBoxExpireMonth, TextBoxExpireYear, TextBoxCVV2.
The field names in the DataTable (dbTable) are: nameCOMPANY, nameLAST, nameFIRST, nameSALUTATION, ccType, ccNumber, ccExpireMonth, ccExpireYear, ccCode.
IMAGE 1:
IMAGE 2:
Have you tried this?
TextBox1.Text = dbTable.Rows(0)("ColumnName").ToString()
TextBox2.Text = dbTable.Rows(1)("OtherColumnName").ToString()
You can also do this:
Dim row as DataRow = dbTable.Rows(0)
TextBox1.Text = row("ColumnName").ToString()
row = dbTable.Rows(1)
TextBox2.Text = row("OtherColumnName").ToString()
You could also DataBind to a DataGrid (or similar control) using dbTable as the DataSource and then set the DataGrid.EditMode to True. This would create the textbox controls for you.
UPDATE:
Try something like this to bind your textboxes to the selected values of your ListView:
Private Sub ListView1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListView1.SelectedIndexChanged
Dim item As ListViewItem = Nothing
Dim tb As TextBox = Nothing
Dim i As Integer = 0
For Each item In ListView1.SelectedItems
tb = Me.Controls.Find("TextBox" & i.ToString, True)(0)
If tb IsNot Nothing Then
tb.Text = item.Text
End If
i += 1
Next
End Sub
UPDATE:
This is a little more error-proof, but this routine will only work if your textboxes are named TextBox1, TextBox2, TextBox3, etc.:
Private Sub ListView1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListView1.SelectedIndexChanged
Dim item As ListViewItem = Nothing
Dim found() As Control = Nothing
Dim tb As TextBox = Nothing
Dim i As Integer = 0
For Each item In ListView1.SelectedItems
found = Me.Controls.Find("TextBox" & i.ToString, True)
If found.Length > 0 Then
tb = TryCast(found(0), TextBox)
Else
tb = Nothing
End If
If tb IsNot Nothing Then
tb.Text = item.Text
End If
i += 1
Next
End Sub
UPDATE:
Okay, thanks to the screenshots, I am assuming that your ListView.MultiSelect = False, so only one item can be selected at a time. Given that, the following should work as long as the textboxes and ListView columns are named correctly:
Private Sub ListView1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListView1.SelectedIndexChanged
Dim item As ListViewItem = Nothing
If ListView1.SelectedItems.Count = 1 Then
item = ListView1.SelectedItems(0)
txtCardNumber.Text = item.SubItems("CARD NUMBER")
txtCardExpirationMonth.Text = item.SubItems("EXP MO")
txtCardExpirationYear.Text = item.SubItems("EXP YEAR")
End If
End Sub
Hello guys/gals,
With tremendous assistance from Pete, I was able to modify the suggested answer and I achieved the desired solution. To prevent the horizontal scrollbars from displaying, I didn't add columns to the Listview (from the Designer). Instead, I added the fields to the Listview programatically - this way they were available for selection.
The main trouble I ran into was figuring out the Index numbers of the fields. I had to debug several times to figure out what the numbers were - so if anybody knows of a better way please do share.
Here're the two codes I used (thanks Pete):
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"))
.Add(dbTable.Rows(i)("ccCode"))
.Add(dbTable.Rows(i)("ccType"))
.Add(dbTable.Rows(i)("ccAuthorizedUseStart"))
.Add(dbTable.Rows(i)("ccAuthorizedUseEnd"))
.Add(dbTable.Rows(i)("nameCOMPANY"))
.Add(dbTable.Rows(i)("nameSALUTATION"))
.Add(dbTable.Rows(i)("nameLAST"))
.Add(dbTable.Rows(i)("nameFIRST"))
End With
End With
Next
If dbTable.Rows.Count = 0 Then
LabelNoCard.Visible = True
LabelNoCard.Focus()
TextBoxAccount.Focus()
Me.Refresh()
Else
If dbTable.Rows.Count > 1 Then
LabelNoCard.Visible = False
LabelMultipleCards.Visible = True
ListViewCard.Visible = True
Me.Refresh()
End If
End If
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
Here's the second one:
Private Sub ListViewCard_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListViewCard.SelectedIndexChanged
GroupBox2.Visible = True
Dim item As ListViewItem = Nothing
If ListViewCard.SelectedItems.Count = 1 Then
item = ListViewCard.SelectedItems(0)
TextBoxCustomer.Text = item.SubItems(8).Text
TextBoxLastName.Text = item.SubItems(10).Text
TextBoxFirstName.Text = item.SubItems(11).Text
ComboBoxSalutation.Text = item.SubItems(9).Text
ComboBoxCardType.Text = item.SubItems(5).Text
TextBoxCard.Text = item.SubItems(1).Text
TextBoxExpireMonth.Text = item.SubItems(2).Text
TextBoxExpireYear.Text = item.SubItems(3).Text
TextBoxCVV2.Text = item.SubItems(4).Text
DateTimePickerStartDate.Text = item.SubItems(6).Text
DateTimePickerEndDate.Text = item.SubItems(7).Text
End If
End Sub