This is a pre-assignment for a class I'm in. Supposed to be pretty simple and act as a warm-up, but I can't get it working. Basically the code is bringing in a test database and performing a calculation. In this case I'm trying to find the highest average batting average in a set of baseball players.
So my end result should be the name of the player with the highest batting average, or a few players if they are tied for the highest average.
Here is the code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As DataTable = New DataTable()
Dim connStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Baseball.accdb"
Dim sqlStr As String = "SELECT * FROM Players"
Dim dataAdapter As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sqlStr, connStr)
dataAdapter.Fill(dt)
dataAdapter.Dispose()
Dim average, pastAverage, highestAverage As Double
For i As Integer = 0 To dt.Rows.Count - 1
average = CDbl(dt.Rows(i)("hits/atBats"))
If average > pastAverage Then
highestAverage = average
End If
pastAverage = average
Next
For i As Integer = 0 To dt.Rows.Count - 1
If dt.Rows(i)("hits/atBats") = highestAverage Then
lstBoxHighest.Items.Add(dt.Rows(i)("name"))
End If
Next
End Sub
End Class
The debugger won't go past the "average = Cdbl(dt.Rows(i)("hits/atBats"))" line in the first For Loop. Can I not do calculations like that in the loop? I am sure the column titles (hits and atBats are correct)
The database looks like this in case you were wondering:
name Team atBats hits
Derek Jeter New York Yankees 511 158
Joe Mauer Minnesota Twins 545 174
etc...
Thanks!
you are missing some object refs:
average = CDbl(dt.Rows(i).item("hits") / dt.Rows(i).item("atBats"))
and like that for the rest of them. VB needs an dt.Rows(i) reference because those are 2 different columns. With "hits/atBats", it cant know those are individual columns.
Shorthand, but kind of masks that they are different cols/items is like you had it:
average = CDbl(dt.Rows(i)("hits") / dt.Rows(i)("atBats"))
Disclaimer: it's not a direct answer to the question.
Instead of pulling all the data to the client and then using two loops to find a name you can do all calculations on db-side and grab only needed rows and columns (in your case just name) with a query that may look like
SELECT name
FROM Players
WHERE atBats / hits =
(
SELECT MAX(atBats / hits)
FROM Players
)
Output:
| NAME |
|-------------|
| Derek Jeter |
Related
I'm using VB.net and SQL for my project. I give a situation for my problem:
Table Quantity
id Pro_no Quantity
1 123 4
2 456 5
Table insertData
id Pro_no Quantity Description
1 123 2 broken
2 123 1 missing part
As you can see user has inserted Pro_no for 123 into the insertData table. Meaning that it has 1 more Quantity can be inserted. My problem is when there are 2 users OR user open the same data with 2 tabs, want to insert the data at the same time, one of them OR one of the tab will not successful to do it cause it has reached the limit.
SQL :
INSERT INTO insertData (Pro_no, Quantity,Description)
VALUES ('123','1','broken')
VB.net
Protected Sub btnCreate_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
If ErrorChecking() = True Then
DataInsert()
DisplayMessage("success", "Done", "Data Succesfully Inserted!")
clearAll()
End If
End Sub
DataInsert() Function :
Private Function DataInsert() As Integer
Using create As New clsQuantityProject_dal
Dim obj As New clsQuantityProject_info
With obj
.Part_No = txtPartNo.Text
.Description = txtDesc.Text
.QTY = spinEditQTY.Text
End With
Dim strResult As Integer = create.QuantityDataInsert(obj)
End Using
Return 1
End Function
note: do tell me if you can't understand my question, I'll correct and explain it better
Can you tell me how to get ages from 0-5 and so on from sql server and input the total in a textbox or label? please click the link for sample
Generate Ages
thank you!
Do you mean something like
Dim sql As String = "SELECT age_column FROM your_table WHERE age_column BETWEEN '0' AND '5'"
'The above line selects the all records where age is between 0-5 (Change the variables)
Dim da As New OleDbDataAdapter(sql, connectionstring)
Dim ds As New DataSet
Dim dt as new DataTable
da.Fill(ds)
dt = ds.Tables(0).Copy()
' Above code stores the results in an iterable table
Dim i As Integer = 0
For Each dr as DataRow in dt.Rows
i = i + 1
Next
TextBox1.Text = i
'i will be the total number of records where age is between 0-5, and display it in a `TextBox`
Your question is, however, very poor, and normally people would not put too much effort into answering it, since you've put no effort in yourself.
I am very new to linq and would like to do the following. Create an array of 11 elements (that works ok) contains random number from 20 to 35 without duplicates. The code I have only gives me random number from 0 to 9.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim r As New Random
'Create an array of exclusive numbers from 0 to 10
Dim exclusive_numbers() As Integer = Enumerable.Range(0, 10).OrderBy(Function(n) r.Next(20, 35)).ToArray
For x = 0 To 10
MsgBox (exclusive_numbers(x).ToString )
Next
End Sub
I would really like to make this work, but I fear it is over my head at this time. Any help, ideas or working code would be appreciated.
thanks
george
Dim r As New Random()
Dim exclusive_numbers As Integer() = Enumerable.Range(20, 16).OrderBy(Function(n) r.Next).Take(11).ToArray()
Will generate 11 random numbers in the range of 20->20+16-1 => 20=>35
The reason yours is giving 0-9 still is because that is what you are specifying the Enumberable Range of numbers to be (start at 0, generate 10 integers, then randomly sort)
#JoelCoehoorn metions below that order by Random.Next() could cause an Exception. Another way to do this would be to order by a Guid.NewGuid().
Enumerable.Range(20, 16).OrderBy(Function(t) Guid.NewGuid()).Take(11)
Okay, so I've got a datagrid view DataGridView1 which is something like the below example.
Name Points
Jack 15
zack 19
Cody 05
I want to be able to count the average of all of the points, However the amount of points will be dynamic and change from time to time. So my solution must be able to work even if there's just two numbers and when there's upwards of 20.
I have been looking a round for a way of doing this, but most posts are only relevant if the amount of 'points' are static. And a lot of the solutions appear to be written in C++, which isn't too much use to a newbie coder like myself on Visual Basic.
So could anyone help me out here?
I would force it to draw a nice extra line in the data grid, by using a union select and a blanks for each column in the sqldatabind. This would add a nice row to the dataset be formatted as a totals row.. You may need to number the rows so your totals row is last most because of ordering. add the term 'Total' as a control in the results or handle it another way.
After that its just a bit of tweaking when your grid draws the row..
something like ...
Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim dRow As GridViewRow = sender
If dRow.RowType = DataControlRowType.DataRow Then
If dRow.Cells(0).Text = "Total" Then
Dim rx As Integer
Dim TotalValue As Double = 0
For rx = 0 To GridView1.Rows.Count - 2
TotalValue += CDbl(GridView1.Rows(rx).Cells(1).Text)
Next
dRow.Cells(1).Text = FormatNumber(TotalValue, 2)
End If
End If
End Sub
Lets say I have a dataset with I dunno 20 records in it.
How do I get to the 16th record in the dataset or the Nth? So any number from 1 to 20
I have spent most of this week trying to think of a method and so far I have gotten no where.
I want the 16th record down in this dataset and there doesn't seem to be a specific command for it.
I'm working in VB.NET with OLE commands.
I'm not sure any code would be of any use to help solve this but I'm populating the dataset something like this:
SQL_Str = "SELECT FROM A TABLE WHERE CRITERIA IS MET"
dbDataAdapter = New OleDbDataAdapter(SQL_Str, dbConnector)
dbDataAdapter.Fill(DataSet, "SelectedRecords")
Now what do I do to get to the 16th row in this dataset knowing that there is 20 records in the dataset?
Since you say you are using VB.NET, just read the row from the dataSet.
Private Function GetRow(ByVal ds As Data.DataSet, ByVal rowNum As Integer) As Data.DataRow
Dim result As Data.DataRow = Nothing
Dim table As Data.DataTable = ds.Tables(0)
result = table.Rows(rowNum)
Return result
End Function
There are overloads to DataSet.Tables: Consider: