VB.net Updating Datatable error Index was outside the bounds of the array - vb.net

I am trying to update the "qnty" column of a specific row in ds.Tables(0) but I don't know why this problem appear even though "qnty" in ds.Table(0) exist?
"Index was outside the bounds of the array."
I use VS 2012, VB.NET
Dim Minus_qnty As String
Dim Row() As Data.DataRow
Row = ds.Tables(0).Select("Prodno = '" & ProdItem_No & "'")
Dim ds_qnty As String = ds.Tables(0).Rows(0)("qnty").ToString()
Minus_qnty = ds_qnty + Prod_taken_qnty
Row(0)("qnty") = Minus_qnty 'The problem appear in this line

Change your last line to check for row length
If Row.Length > 0 Then Row(0)("qnty") = Minus_qnty

The error is because there are no records in the DataTable matching your condition Prodno = ProdItem_No.
I think this is what you wanted to do:
Dim Minus_qnty As String
Dim Row() As Data.DataRow
Row = ds.Tables(0).Select("Prodno = '" & ProdItem_No & "'")
If Row.Length > 0 Then
Dim ds_qnty As String = Row(0)("qnty").ToString()
Minus_qnty = ds_qnty + Prod_taken_qnty
Row(0)("qnty") = Minus_qnty
End If
Or maybe simply this:
Dim Row() As Data.DataRow = ds.Tables(0).Select("Prodno = '" & ProdItem_No & "'")
If Row.Length > 0 Then
Row(0)("qnty") = Row(0)("qnty") + Prod_taken_qnty
End If

Related

Update datatable and show new value

I am trying to update datatable and print out updated row but I am getting an old value. Here is my code:
Public Shared zadnjiBrojevi As DataTable
...
aaaa.ItemsSource = Globals.zadnjiBrojevi
Dim lastnr As Integer
Dim result() As DataRow = Globals.zadnjiBrojevi.Select("tip = " & tipoviDokumenataCbox.SelectedItem.tag & "")
For Each row As DataRow In result
lastnr = row(1)
Next
Console.WriteLine("Last number is: " & lastnr)
Dim myRow() As Data.DataRow
myRow = Globals.zadnjiBrojevi.Select("tip = '" & tipoviDokumenataCbox.SelectedItem.tag & "'")
myRow(0)("lastnr") = myRow(0)("lastnr") + 1
Dim filename As String = Globals.rootPath & "ZadnjiBrojevi.xml"
Globals.zadnjiBrojevi.WriteXml(filename, XmlWriteMode.WriteSchema)
Console.WriteLine("Dodan upis!")
In console i am always getting "Last number is: 4443". But GridControl "aaaa" shows updated values. And "writexml" writes updated values.

Join string with specific word for RowFilter

I have rowfilter which i use to filter my datasource. I have couple controls which user can pick up checking specific checkboxes either to be used for Rowilter or not. Below code.
Dim ds = CType(dgvAbmessungen.PrimaryGrid.DataSource, DataSet)
Dim dtMain As DataTable = ds.Tables(0)
Dim filterStr As String = String.Empty
Dim byNummer As String = " [Nummer] like '" & txtFilterByNummer.Text.Trim() & "%'"
Dim byUser As String = " [User] = '" + cbUser.Text
Dim byCreateDateFrom As String = " [CreateDate] >= '" + CType(Convert.ToDateTime(calFrom.Value.Date), String)
Dim byCreateDateTo As String = "' ([CreateDate] < '" + CType(Convert.ToDateTime(calTo.Value.Date), String)
'select case checboxes and construct final rowfilter's string
dtMain.DefaultView.RowFilter = filterStr
Checboxes for diffrent controls to be checked:
for Nummer there is checkboxNummer
for User there is checkboxUser
for CreateDateFrom there is checkboxCreateDateFrom
for CreateDateTo there is checkboxCreateDateTo
Target is user checks one or more checboxes and filter should be constructed (string). Problem is i have no idea how to also concat "And" keywords between strings if user check more than one diffrent checboxes.
Currently i try to do it using select case. What could be the most efficient way to do so?
I would use LINQ:
Dim data = dtMain.AsEnumerable()
If checkboxNummer.Checked Then
data = data.Where(Function(row) row.Field(Of String)("Nummer").Contains(txtFilterByNummer.Text.Trim()))
End If
If checkboxUser.Checked Then
data = data.Where(Function(row) row.Field(Of String)("User") = cbUser.Text.Trim())
End If
If CreateDateFrom.Checked Then
data = data.Where(Function(row) row.Field(Of Date)("CreateDate") >= calFrom.Value.Date)
End If
If CreateDateTo.Checked Then
data = data.Where(Function(row) row.Field(Of Date)("CreateDate") < calTo.Value.Date)
End If
If you need the result as DataRow() use data.ToArray(). If you need a DataTable use:
If data.Any() Then dtMain = data.CopyToDataTable()

SQL Server (specific) table not updating

I am having a really strange issue with classic asp insert/update that worked flawlessly for years and was never altered. Out of the blue, the table is no longer updating or taking new records. The code does not throw any errors and the SQL Server log shows no errors either. Other tables in the same database work fine so I can insert and update without issues.
Is there a way to find out what is happening with this table or whether it is locked for some reason. I restarted SQL Server and web application, even the server and no luck.
I updated the table directly in SQL Server and it updates and inserts new records fine.
I used the same code on another table and was able to update records.
Can someone please point me in the right direction as I am out ideas on what may be causing this.
Thanks in advance.
Here is the code:
<%
' *** Edit Operations: (Modified for File Upload) declare variables
Dim MM_editAction
Dim MM_abortEdit
Dim MM_editQuery
Dim MM_editCmd
Dim MM_editConnection
Dim MM_editTable
Dim MM_editRedirectUrl
Dim MM_editColumn
Dim MM_recordId
Dim MM_fieldsStr
Dim MM_columnsStr
Dim MM_fields
Dim MM_columns
Dim MM_typeArray
Dim MM_formVal
Dim MM_delim
Dim MM_altVal
Dim MM_emptyVal
Dim MM_i
MM_editAction = CStr(Request.ServerVariables("SCRIPT_NAME"))
If (UploadQueryString <> "") Then
MM_editAction = MM_editAction & "?" & Server.HTMLEncode(UploadQueryString)
End If
' boolean to abort record edit
MM_abortEdit = false
' query string to execute
MM_editQuery = ""
%>
<%
' *** Insert Record: (Modified for File Upload) set variables
If (CStr(UploadFormRequest("MM_insert")) = "update") Then
MM_editConnection = MM_ar_inventory_STRING
MM_editTable = "Artists"
MM_editRedirectUrl = "artists_add.asp?status=ok"
MM_fieldsStr = "ArtistName|value|WebsiteStatus|value|Biography|value|Notes|value|ImageFileName|value|ModifiedBy|value|DT|value|IpAddress|value"
MM_columnsStr = "ARTST_Artist|',none,''|ARTST_WebsiteStatus|',none,''|ARTST_Biography|',none,''|ARTST_Notes|',none,''|ARTST_ArtistImageFileName|',none,''|ARTST_ModifiedBy|',none,''|ARTST_LastModified|',none,NULL|ARTST_LastModifiedIP|',none,''"
' create the MM_fields and MM_columns arrays
MM_fields = Split(MM_fieldsStr, "|")
MM_columns = Split(MM_columnsStr, "|")
' set the form values
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_fields(MM_i+1) = CStr(UploadFormRequest(MM_fields(MM_i)))
Next
' append the query string to the redirect URL
If (MM_editRedirectUrl <> "" And UploadQueryString <> "") Then
If (InStr(1, MM_editRedirectUrl, "?", vbTextCompare) = 0 And UploadQueryString <> "") Then
MM_editRedirectUrl = MM_editRedirectUrl & "?" & UploadQueryString
Else
MM_editRedirectUrl = MM_editRedirectUrl & "&" & UploadQueryString
End If
End If
End If
%>
<%
' *** Insert Record: (Modified for File Upload) construct a sql insert statement and execute it
Dim MM_tableValues
Dim MM_dbValues
If (CStr(UploadFormRequest("MM_insert")) <> "") Then
' create the sql insert statement
MM_tableValues = ""
MM_dbValues = ""
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_formVal = MM_fields(MM_i+1)
MM_typeArray = Split(MM_columns(MM_i+1),",")
MM_delim = MM_typeArray(0)
If (MM_delim = "none") Then MM_delim = ""
MM_altVal = MM_typeArray(1)
If (MM_altVal = "none") Then MM_altVal = ""
MM_emptyVal = MM_typeArray(2)
If (MM_emptyVal = "none") Then MM_emptyVal = ""
If (MM_formVal = "") Then
MM_formVal = MM_emptyVal
Else
If (MM_altVal <> "") Then
MM_formVal = MM_altVal
ElseIf (MM_delim = "'") Then ' escape quotes
MM_formVal = "'" & Replace(MM_formVal,"'","''") & "'"
Else
MM_formVal = MM_delim + MM_formVal + MM_delim
End If
End If
If (MM_i <> LBound(MM_fields)) Then
MM_tableValues = MM_tableValues & ","
MM_dbValues = MM_dbValues & ","
End If
MM_tableValues = MM_tableValues & MM_columns(MM_i)
MM_dbValues = MM_dbValues & MM_formVal
Next
MM_editQuery = "insert into " & MM_editTable & " (" & MM_tableValues & ") values (" & MM_dbValues & ")"
If (Not MM_abortEdit) Then
' execute the insert
Set MM_editCmd = Server.CreateObject("ADODB.Command")
MM_editCmd.ActiveConnection = MM_editConnection
MM_editCmd.CommandText = MM_editQuery
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close
If (MM_editRedirectUrl <> "") Then
Response.Redirect(MM_editRedirectUrl)
End If
End If
End If
%>
I notice that UploadQueryString is undefined so if you add this as the fist line
<%OPTION EXPLICIT%>
I guess that you will get some meaningful error messages
The craziest solution to the problem that totally seems unrelated was to disable Symantec Endpoint Protection (Network Protection) and it worked for a reason I cannot possibly explain! Thank you all for the suggestions above.

Loop, aggregate and return unique DataRow sum

I have a DataGrid which contains multiple transactions of Customer's buy ins.
What I want is to add up the transaction buy ins from each customer and add the result on the related images. What I have at the moment gives me logic errors i.e. adding the same amounts on more than one images.
Here is the structure of my DataGrid (column titles): [Name,Surname, Buyin, Type, StartTime, TransactionID, CustomerID]
and here is my code:
Dim tbActivePlayers As DataTable = Me.ActivePlayersTableAdapter.GetData()
Dim tbTemp As New DataTable
' table = DataSet.Tables("Orders")
' Declare an object variable.
Dim objTotalBuyin As Object
Dim iCount, ilbl As Integer
ilbl = 1
Dim viewUniquePlayers As New DataView(tbActivePlayers)
Dim iActivePlayers As Integer = viewUniquePlayers.ToTable(True, "CustomerID").Rows.Count
Dim dtDataTable As DataTable = viewUniquePlayers.ToTable(True, "CustomerID")
Dim myLabel As Label
For iCount = 0 To dtDataTable.Rows.Count
objTotalBuyin = tbActivePlayers.Compute("Sum(Buyin)", "CustomerID = " & tbActivePlayers.Rows(iCount).Item("CustomerID"))
'MsgBox("Name: " & tbActivePlayers.Rows(iCount + 1).Item("Name") & ", Sumbuyin:" & sumObject.ToString & " ResultCount:" & ResultCount)
'
myLabel = CType(Me.Controls.Find("lblPlayer" & ilbl, True)(0), Label)
If Not myLabel Is Nothing Then
myLabel.Text = "Empty Seat"
End If
'
myLabel.Text = tbActivePlayers.Rows(iCount).Item("Name") & Environment.NewLine & _
"€" & objTotalBuyin.ToString
myLabel.Image = Global.PokerBusiness.My.Resources.Resources.seatocc
ilbl += 1
Next
Your filter function for the Compute seems to be based off each row in tbActivePlayers, yet you're looping over each row (and thus counting the rows of) a view of unique players. My brain compiler tells me this might well be the source of your logic errors, because you're potentially computing your sum with a filter that's using a single, unique customer ID more than once. Consider changing
objTotalBuyin = tbActivePlayers.Compute("Sum(Buyin)", "CustomerID = " & tbActivePlayers.Rows(iCount).Item("CustomerID"))
To
objTotalBuyin = tbActivePlayers.Compute("Sum(Buyin)", "CustomerID = " & dtDataTable.Rows(iCount).Item("CustomerID"))

for loop for a string variable

this is my code -
for i as integer = 0 to rows.count - 1
output &= "Name =" & row(i)("Name")
output &= "lastName =" & row(i)("lastName")
... 50 more fields
next
i need the output to be like this
Applicant1Name = MikeApplicant1lastName = ditkaApplicant2Name = TomApplicant2lastName = Brady ...
how do i do this without putting the following code 50 times -
output &= "Applicant" & i.tostring() + 1 &"Name =" & row(i)("Name")
... and so on.
is there a way to make a for loop and run applicant 1,2,3,4.... in one shot?
thanks
Try:
Dim output as New StringBuilder("")
For i as Integer = 0 To rows.Count - 1
output.append("Applicant" + i.ToString())
Foreach(col as DataColumn in dt.Columns) ' The datatable where your rows are
Dim colName as string = col.ColumnName
output.append(colName & "=" & rows(i)(colName).ToString())
Next
If i < rows.Count - 1 Then output.Append("|")
Next
StringBuilder is faster for string concatenations, and if you keep your rows in a datatable (which I assume is happening because that's how it looks like you're accessing them), then you can just iterate through the columnnames at the top level.
You really cant as you are trying to append 50 different fields.
The only thing you can shorten is the variable name:
Dim strLN as String = row(i)("lastName")
Dim strFirstName as String = row(i)("firstName")
Then you simply put it all together
output &= strLN & strFirstName...etc
looks like you want to create an array of all the fields you have and then include a nested loop.
Dim fields As String() = {"Name", "LastName", "SSN", "Birthdate"}
Dim output As String = ""
For i As Integer = 1 To rows.count
For Each field As String In fields
output = String.Concat(output, "Applicant ", i, field, "=", row(i)(field), " ")
Next
Next