Sort a Dataset in visualbasic - vb.net

I don't know what i doing wrong. I have been on several forums trying to figure out how to sort a table in visual basic.
I have treid with and with out a dataview, but noting seams to work.
I have a logg that the user can do new inserts in. It has 3 columns. "Date", "Tool", "Comment".
When my VB application loads the program reads the table from a Access database and i get my sorting just fine by the sql phrase:
"select * from Logg ORDER BY Logg.Datum DESC"
After a user have uppdated the table i whant to sort it again. I have treid the following, but nothing happens. The order is the same whatever i do.
DS is my Dataset and dw my dataview, and "Datum" the column i whant to sort
DS.Tables("hela").DefaultView.Sort = "Datum DESC"
dw = DS.Tables("hela").DefaultView
For i = 0 To antal_poss - 1
LOGG(i, 0) = dw.Table.Rows(i).Item(3)
LOGG(i, 1) = dw.Table.Rows(i).Item(1)
LOGG(i, 2) = dw.Table.Rows(i).Item(4)
Next i
What am i doing wrong?

In your code you use the DataView to retrieve the Table and then the DataRows, but you extract them following the order on the DataTable.
You need to loop following the order of the DataView.
Something like this
Dim i As Integer = 0
For Each row As DataRowView in dw
LOGG(i, 0) = row.Item(3)
LOGG(i, 1) = row.Item(1)
LOGG(i, 2) = row.Item(4)
i += 1
Next i
Of course this assume that your LOGG array contains enough entries to accomodate every row retrieved. It is the same number of the rows in the DataTable

Related

How to get Average of records from Access Database in vb.net?

I have a project where I connected an Access Database through a DataGridView. I've made some queries based on info inputed by the user through textboxes and comboboxes. Now I need to find a way to count the Average of the records found after the query from one specific column. Is there a way to do that ?
Store the counts from your queries...
Dim lstCounts As New List(Of Integer)
'Your database retrieval method: SELECT COUNT(*) FROM table WHERE field = 'Blah'
lstCounts.Add(<above result>)
'Your database retrieval method: SELECT COUNT(*) FROM table WHERE field = 'Blah1'
lstCounts.Add(<above result>)
'Your database retrieval method: SELECT COUNT(*) FROM table WHERE field = 'Blah2'
lstCounts.Add(<above result>)
'etc.
Find the average...
Dim nTotal As Integer = 0
Dim dAverage As Decimal = 0.0
For i As Integer = 0 to lstCounts.Count - 1
nTotal += lstCounts(i)
Next
'Make sure you aren't dividing by zero
If lstCounts.Count > 0
dAverage = nTotal / lstCounts.Count
End If
You could also simply just add the total as you perform each query and not bother using a List, but then you need to track how many queries you ran.

Access SQL Randomizer Not working as intended

I'm using the below mentioned code to select a record ID from an Access Database that wasn't already selected in the last day and add it to an array.
The general goal is that a record that matches the initial "Difficulty" criteria will be retrieved so long as either the record was never selected before OR the record wasn't chosen in the last 2 days. After the loop is done, I should have x amount of unique record ID's and add those onto an array for processing elsewhere.
Private Function RetrieveQuestionID(questionCount As Integer)
' We're using this retrieve the question id's from the database that fit our arrangements.
Dim intQuestArray(0 To questionCount) As Integer
Dim QuestionConnection As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = |DataDirectory|\Database\MillionaireDB.accdb;")
QuestionConnection.Open()
For i As Integer = 1 To intNoOfQuestions
'TODO: If there are no valid questions, pull up any of them that meets the difficulty requirement....
Dim QuestionConnectionQuery As New OleDb.OleDbCommand("SELECT Questions.QuestionID FROM Questions WHERE (((Questions.QuestionDifficulty)=[?])) AND (((Questions.LastDateRevealed) Is Null)) OR (Questions.LastDateRevealed >= DateAdd('d',-2,Date())) ORDER BY Rnd((Questions.QuestionID) * Time());", QuestionConnection)
QuestionConnectionQuery.Parameters.AddWithValue("?", intQuestionDifficulty(i - 1).ToString)
Dim QuestionDataAdapter As New OleDb.OleDbDataAdapter(QuestionConnectionQuery)
Dim QuestionDataSet As New DataSet
QuestionDataAdapter.Fill(QuestionDataSet, "Questions")
intQuestArray(i - 1) = QuestionDataSet.Tables("Questions").Rows(0).Item(0)
Dim QuestionConnectionUpdateQuery As New OleDb.OleDbCommand("UPDATE Questions SET Questions.LastDateRevealed = NOW() WHERE Questions.QuestionID = [?]", QuestionConnection)
QuestionConnectionUpdateQuery.Parameters.AddWithValue("?", intQuestArray(i - 1).ToString)
QuestionConnectionUpdateQuery.ExecuteNonQuery()
Next
QuestionConnection.Close()
Return intQuestArray
End Function
However, looping through the array will show that there are records are somehow being repeated even though the record updates during the loop.
Is there another way to loop through the database and pull up these records? I even attempted to move the .Open() and .Close() statements to within the For...Next loop and I'm given worse results than before.
As Steve wrote, the >= should be a < .
In addition, your WHERE clause is missing parentheses around the OR part.
It should be (without all unnecessary parentheses):
SELECT Questions.QuestionID
FROM Questions
WHERE Questions.QuestionDifficulty=[?]
AND ( Questions.LastDateRevealed Is Null
OR Questions.LastDateRevealed < DateAdd('d',-2,Date()) )
ORDER BY Rnd(Questions.QuestionID * Time());
Also have a look at How to get random record from MS Access database - it is suggested to use a negative value as parameter for Rnd().

Unable to read new records from a table

I have a data adapter with 4 tables in a dataset. When I update a new record to the table it appears in the SQL database and the associated datagridivew has been reloaded with the dat in the table, but when I try and read the new record using the following code it can't find the record.
Dim row As DataRow = dsSrvAV.Tables("ServiceAvailability").Select("ID = " & intRecordID).FirstOrDefault()
The same code is used to read other records that were in the database when the application opened, it's just new records that it can't read.
This is the code that writes the new records
Dim newAvailability As DataRow = dsSrvAV.Tables("ServiceAvailability").NewRow()
'Add some data to it
newAvailability("Service_ID") = cboServices.SelectedValue
newAvailability("Date") = Format(dtpDate.Value.ToString, "Short Date")
newAvailability("Downtime") = nudDowntime.Value
newAvailability("Notes") = txtNotes.Text
newAvailability("MajorIncident") = txtMajorIncident.Text
newAvailability("ActionsTaken") = txtActionsTaken.Text
newAvailability("Type") = cboType.SelectedValue
newAvailability("Root_Cause") = txtRootCause.Text
'Add it to the table
dsSrvAV.Tables("ServiceAvailability").Rows.Add(newAvailability)
'Update the adapter
daSrvAv.Update(dsSrvAV, "ServiceAvailability")
dsSrvAV.Tables("ServiceAvailability").AcceptChanges()
Can anyone offer any thoughts as to why this won't allow new records to be read back.
Thanks
Rich
Per comments - this solved the issue.
Close your dsSrvAv dataset, and then re-open it, and then do the select.
Regardng performance: are you adding 1 record per second of 1,000,000. If its 1,000,000 then yes there's an overhead. If its 1 per second there isn't any noticable overhead.

How to sort a column in dataset VB.NET having multiple sort conditions

I have a dataset in which there is a column contains various string type values like below:
Aircraft
Crime
Package Total
Apartments
DIC - Personnel
Now the requirement is that after applying sorting logic on this colum if there is a "Package Total" value in it then it must come at the top position on the Dataset and after that all other values should be in alphabatically sorted order like below:
Package Total
Aircraft
Apartments
Crime
DIC - Personnel
We have used in Database below logic which is working fine but can't figure it out how to do it on Dataset VB.net from Fronend side:
ORDER BY
CASE WHEN UseCarrierAllocation = 0 THEN
CASE WHEN InvoiceItemLevel LIKE 'Package Total%' THEN 0 ELSE 1
END
END, InvoiceItemLevel ASC
Any reply/idea will be helpful!
Something like this might work for you:
DataView dv = sDataSet.Tables("Table1").DefaultView;
dv.Sort = "column1";
YourDatasourceName.YourDatasetName.DefaultView.Sort = "YourColumnName"
YourDataTableName = YourDatasourceName.YourDatasetName.DefaultView.ToTable(True, "YourColumnName")

Concurrency violation - the UpdateCommand affected 0 of the expected 1 records

I am working on a VB.NET project and I am trying to Insert / Update some rows in the SQL DB.
To do this I use the code below to bring back a dataset based on 3 parameters.
If the dataset brings no data back, then the code simply inserts a new row.
This works fine.
However, if the data brings a row back (meaning the row already exists in the table) then I want to update one of the values instead.
This is where I'm getting the error in the title of this post.
Can anyone help me with where I'm going wrong please?
Thank you in advance.
Dim x_Update As Boolean
AdaptSql = New Data.AdapterX(SQL_ConnectionString)
DS = New DatsetX
AdaptSql.Fill(DS, Number, PeriodID, TypeID)
If DS.tbl_A.Count > 0 Then
x_Row = DS.tbl_A(0)
x_Row.BeginEdit()
x_Update = True
Else
x_Row = DS.tbl_A.NewRow
End If
x_Row.Number = Number
x_Row.DateID = PeriodID
x_Row.TypeID = TypeID
x_Row.Value = Value
x_Row.UpdatedDate = Date.Now
If x_Update = False Then DS.tbl_A.Addtbl_ARow(x_Row)
x_Row.EndEdit()
AdaptSql.Update(DS)
x_Row = Nothing
DS.Dispose()
AdaptSql = Nothing
check the x_Row.RowState before call AdaptSql.Update(DS), for a newly created row, the row state should be "Added", while an existing record should have "Modified" since there was some updates to it.