Update datatable and show new value - vb.net

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.

Related

Loopings in VB.net with two text boxes

I have two text boxes in a user-input form asking for a VisitID(s) and to set a price.
It then uses the following code to update each VisitID with a single price.
myCmd1.CommandText = "UPDATE tblVisit SET Price = (" & CustomerRefString & ") WHERE VisitID IN (" & VisitIDString & ")"
I understand that the above code loops for each VisitID in the VisitIDString, but how do I loop to allow updating each visitID with the corresponding line in the Price TextBox?
Private Sub btnOk_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim VisitIDString AS String
Dim VisitIDsUpdated As Object
Dim myComma() As Char = {","}
Dim connString As String
Dim DataSourceBase = Report.GetDataSource("Connection")
Dim ConnectionCollection = Report.Dictionary.Connections
connString = ConnectionCollection(0).ConnectionString
VisitIDString = VisitIDTextBox.Text
VisitIDString = VisitIDString.Replace(vbCr, "").Replace(vbLf, ",")
VisitIDString = VisitIDString.Replace(" ", "")
VisitIDString = VisitIDString.TrimEnd(MyComma)
Report.SetParameterValue("VisitIDByte",VisitIDString)
'------------------------------------------------------------------------------------------------------------
Dim CustomerRefString AS String
Dim CusterRefUpdated As Object
Dim myCommaRef() As Char = {","}
'------------------------------------------------------------------------------------------------------------
CustomerRefString = CustomerRefTextBox.Text
CustomerRefString = CustomerRefString.Replace(vbCr, "").Replace(vbLf, ",")
CustomerRefString = CustomerRefString.Replace(" ", "")
CustomerRefString = CustomerRefString.TrimEnd(MyComma)
'------------------------------------------------------------------------------------------------------------
myConn = New SqlConnection(connString) 'after changes
'Create a Command object
myCmd1 = myConn.CreateCommand
myCmd1.CommandText = "UPDATE tblVisit SET Price = (" & CustomerRefString & ") WHERE VisitID IN (" & VisitIDString & ")"
'Open the connection.
myConn.Open()
'Execute the statement and return a single value. If you wanted to return more than 1 value you need to add a loop here.
VisitIDsUpdated = myCmd1.ExecuteScalar()
'Close the database connection.
myConn.Close()
End Sub
There are better ways to create your user interface, but if you have to do it this way (with textboxes), then you can solve the problem easily as long as the user enters the data correctly.
Assuming you have "id" and "price" data that looks something like this:
---------
|ID|PRICE|
---------
|11|1.11 |
|22|2.22 |
|33|3.33 |
---------
The user would paste these values into the VisitIDTextBox textbox:
11
22
33
And the user would paste these values into the Price textbox:
1.11
2.22
3.33
Then your solution relies on the fact that the index number of the item in the VisitIDTextBox textbox would match the index number of the item in the Price textbox.
So you would convert the contents of both textboxes into an array. Below is a simple example of you can do that for the VisitIDTextBox textbox.
'Any character in this array will be used to split the string
Dim sAAA As String = ",|" & vbCrLf
Dim arSplitOnValues() As Char = sAAA.ToCharArray()
'Create an array of visit ID's
Dim arVisitIDs() As String = VisitIDTextBox.Text.Split(arSplitOnValues, System.StringSplitOptions.RemoveEmptyEntries)
After doing the same for the values in the Price textbox, you would now have two arrays; arVisitIDs and arPrices
The index of each item in the arrays would now match up, so you can select from arVisitIDs and arPrices using the same index and get the price that matches the ID.
You can see this by using a simple loop like this:
For iLpr As Integer = 0 To arVisitIDs.GetUpperBound(0)
MessageBox.Show(Me, arVisitIDs(iLpr) & "~" & arPrices(iLpr), "Test", MessageBoxButtons.OK, MessageBoxIcon.Information)
Next iLpr
When run, you'll get three messageboxes with values like this:
11~1.11
22~2.22
33~3.33

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

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

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"))

VB.NET create datatable?

I am trying to create a datatable in VB.NET, but when I output a row from this table it shows: "System.Data.DataRow".
I have compared my code to several websites and it seems correct. However if I instead Response.Write these values they display correctly.
So here is my code:
Sub Page_Load(Sender as Object, E as EventArgs)
If Not IsPostback Then
...
End If
Main
End Sub
Sub Main()
Dim FirstMonthDate As Date = CDate("1/1/" & dYear.SelectedValue)
Dim LastMonthDate As Date = GlobalFunctions.GlobalF.MonthLastDate(dYear.SelectedValue & "-" & dEndMonth.SelectedValue & "-1")
Dim TheGroup As String
Dim LastWeek As String
Dim FirstWeek As String
Dim dLastWeek As Date
Dim dFirstWeek As Date
Dim iWeek As String
Dim commandstring As String = "SELECT cast(DateDiff(wk, '1/1/2011', '" & LastMonthDate & "') as varchar(30)) AS SELECTED_WEEK "
Dim DSDateData As New System.Data.DataSet
DSDateData = GlobalFunctions.GlobalF.GetDevSQLServerDataSet(commandstring)
Dim dRow As DataRow
For Each dRow In DSDateData.Tables(0).Rows
iWeek = dRow("SELECTED_WEEK")
Next
Dim FirstYearDate As Date = CDate("1/1/" & dYear.SelectedValue)
commandstring = "SELECT DateAdd(ww, " & iWeek & ", '" & FirstYearDate & "') AS LAST_WEEK "
Dim DSDateData2 As New System.Data.DataSet
DSDateData2 = GlobalFunctions.GlobalF.GetDevSQLServerDataSet(commandstring)
For Each dRow In DSDateData2.Tables(0).Rows
LastWeek = dRow("LAST_WEEK")
Next
dLastWeek = CDate(LastWeek)
commandstring = "SELECT DATEADD(dd, -1, DATEADD(wk, DATEDIFF(wk,0, dateadd(dd,6-datepart(day,'" & LastMonthDate & "'),'" & LastMonthDate & "') ), 0)) AS FIRST_WEEK "
Dim DSDateData3 As New System.Data.DataSet
DSDateData3 = GlobalFunctions.GlobalF.GetDevSQLServerDataSet(commandstring)
For Each dRow In DSDateData3.Tables(0).Rows
FirstWeek = dRow("FIRST_WEEK")
Next
dFirstWeek = CDate(FirstWeek)
dFirstWeek = DateAdd(DateInterval.WeekOfYear, -1, dFirstWeek)
Dim arrDayYear As New ArrayList()
Dim dFirstDay As New Date
Dim arrList As ArrayList = New ArrayList()
Dim dt2 As New DataTable
Dim sWeek As DataColumn = New DataColumn("sWeek")
sWeek.DataType = System.Type.GetType("System.String")
Dim sDay As DataColumn = New DataColumn("sDay")
sDay.DataType = System.Type.GetType("System.String")
dt2.Columns.Add(sWeek)
dt2.Columns.Add(sDay)
Response.Write("NW1")
Dim dr As DataRow
dr = dt2.NewRow()
dr("sWeek") = "New week"
dr("sDay") = "New day"
dt2.Rows.Add(dr)
Response.Write(dr)
Response.Write("<br>")
dFirstDay = dFirstDay.AddDays(1)
...
End Sub
...
It's this last Response.Write that is causing the "System.Data.DataRow". But the Response.Write before this (NW1) does print. So what am I doing wrong?
Your code is correct.
Calling Response.Write(dr) prints dr.ToString().
Since DataRow doesn't override ToString(), it jsut returns the typename.
You probably want to prin the value of a column.
You must iterate the data rows or select a specific data row. Iterating and outputing the values would be like so:
//c#
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
Console.WriteLine(row[col]);
}
//VB.Net
For Each (row As DataRow In dt.Rows)
For Each (col As DataColumn In dt.Columns)
Console.WriteLine(row[col])
Next
Next
To print just the first row:
DataRow row = dt.Rows[0];
foreach (DataColumn col in row.Columns)
Console.WriteLine(row[col]);
Response.Write() Needs a string, so it is converting your variable (dr) to a string. The default "toString" method just uses the name of the class. In this case "System.Data.DataRow"
It seems like you might want to loop over the row and output each value individually something like...
For Each element In dr.ItemArray
Response.Write(element)
Next
Response.Write("<br>")

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