How to manipulate DataSet - vb.net

i have problem in manipulating DataSet, how can i filter rows without getting the whole records in tables.
here is my codes:
For j As Integer = 0 To sDataSet.Tables(tran_ar_so_t.Name).Rows.Count - 1
Dim nQty, nPrice, nAmount As Double
With sDataSet.Tables(tran_ar_so_t.Name)
nQty = IIf(.Rows(j).Item("nQty") Is DBNull.Value, 0, .Rows(j).Item("nQty")) : nPrice = IIf(.Rows(j).Item("nPrice") Is DBNull.Value, 0, .Rows(j).Item("nPrice"))
ComputeNet(j)
nAmount = net * nQty
.Rows(j).Item("nAmountDue") = nAmount
End With
Next

Maybe DataTable.Select() method can resolve your problem; check this example:
Dim filterCondition As String = "nQty > 10" 'A where statement you need
Dim filteredRows As DataRow() = sDataSet.Tables(tran_ar_so_t.Name).Select(filterCondition)
Replace "nQty > 0" with your filtered condition, then in filteredRows you'll find only the DataRow that match with given condition.

Related

random and shuffle questions vb

i'm puzzled in the logic of shuffling the questions that i'll display from my database.
my current code displays random questions to the textbox but it also display empty and duplicate entries.
Dim r As MySqlDataReader
Dim i As Integer = 0
Dim temp() As Integer = {}
Dim txtQ() As TextBox = {txtQ1, txtQ2, txtQ3, txtQ4, txtQ5, txtQ6, txtQ7, txtQ8, txtQ9, txtQ10}
Dim cbA() As CheckedListBox = {cbA1, cbA2, cbA3, cbA4, cbA5, cbA6, cbA7, cbA8, cbA9, cbA10}
con.Open()
cmd = New MySqlCommand("select * from tbexam", con)
r = cmd.ExecuteReader
While r.Read
If i <= 9 Then
Randomize()
Dim j As Integer = CInt(Int(9 * Rnd()))
txtQ(j).Text = r.GetString("exam_question")
cbA(j).Items.Clear()
cbA(j).Items.Add("a) " & r.GetString("exam_ans_a"))
cbA(j).Items.Add("b) " & r.GetString("exam_ans_b"))
cbA(j).Items.Add("c) " & r.GetString("exam_ans_c"))
cbA(j).Items.Add("d) " & r.GetString("exam_ans_d"))
i = i + 1
End If
End While
When you place a random number in j, it is (very nearly) a random number between 0 and 9. This is equivalent to rolling a ten-sided dice. What do you think the chances are that if you were to roll it ten times you would get exactly one of each of the values 0 to 9? Pretty low. What you will actually get is something like: 2, 0, 8, 2, 5, 1, 7, 6, 1, 4. This sequence contains duplicates of 2 and 1 and the values 3, and 9 do not appear. This is where your duplicates and gaps come from.
One option you could try is to fill the array sequentially and then shuffle it.
Dim r As MySqlDataReader
Dim i As Integer = 0
Dim temp() As Integer = {}
Dim txtQ() As TextBox = {txtQ1, txtQ2, txtQ3, txtQ4, txtQ5, txtQ6, txtQ7, txtQ8, txtQ9, txtQ10}
Dim cbA() As CheckedListBox = {cbA1, cbA2, cbA3, cbA4, cbA5, cbA6, cbA7, cbA8, cbA9, cbA10}
con.Open()
cmd = New MySqlCommand("select * from tbexam", con)
r = cmd.ExecuteReader
' Read the Q&As into the arrays in the order they appear in the DB
While r.Read
If i <= 9 Then
txtQ(i).Text = r.GetString("exam_question")
cbA(i).Items.Clear()
cbA(i).Items.Add("a) " & r.GetString("exam_ans_a"))
cbA(i).Items.Add("b) " & r.GetString("exam_ans_b"))
cbA(i).Items.Add("c) " & r.GetString("exam_ans_c"))
cbA(i).Items.Add("d) " & r.GetString("exam_ans_d"))
i = i + 1
End If
End While
' Re-order the arrays by swapping each element with another, randomly selected element.
' Start with i at the count of the elements read in the last loop and work down.
Dim n as Integer = i - 1
While i > 0
Dim j As Integer = CInt(Int(n * Rnd()))
i = i - 1
' Swap elements i and j of the arrays
Dim tmpQ As TextBox = txtQ(i)
txtQ(i) = txtQ(j)
txtQ(j) = tmpQ
Dim tmpA() As CheckedListBox = cbA(i)
cbA(i) = cbA(j)
cbA(j) = tmpA
End While
This could be simplified and abstracted but you get the idea.
It is hard to avoid duplicate entry using random number generation, but you can avoid empty entries. You get empty entries because you generates random number and fetch question with that id, and unfortunately that id is not available in database always. SO first, fetch all the ids from database in an array and generate random number from 0 to array length. and select id value of array key.

converting dataset.Compute("Sum(TARGET_AREA)", "") to .toString("N")

I am trying to convert my computed database columns in my datagrid. I was able to compute the columns and wanted to fix the format of the results.
Label18.Text = dataset.Compute("Sum(TARGET_AREA)", "") & " (ha)"
An example of my output is 100000.00 (ha)
What I wanted for my output is to look like this 100,000.00 (ha)
I tried using .toString("N") but no luck.
my column type is Decimal and the others were Double.
Any idea on how to fix it?
You could use String.Format method.
Example
value = 1234.567890
Console.WriteLine(value.ToString("0,0.00", CultureInfo.InvariantCulture))
Source: MSDN Custom Numeric Format Strings.
Here is an example using a DataTable - Note that you may want to check the sum if the column allows nulls. Also, the sum here is invoked over the datatable object not the dataset (as in your question) - This code has been automatically translated from C# - I assume it syntactically OK.
Dim dataset As New DataSet("ds1")
Dim dt As New DataTable("dt")
Dim dc As DataColumn = dt.Columns.Add("TARGET_AREA", GetType(System.Decimal))
Dim dr As DataRow = dt.Rows.Add()
dr("TARGET_AREA") = 100000.0
Dim finalResult As String = ""
Dim value As Decimal
If dt.Rows.Count > 0 Then
Dim result_obj As Object = dt.Compute("Sum(TARGET_AREA)", "")
If result_obj Is System.DBNull.Value Then
value = 0
Else
value = Convert.ToDecimal(result_obj)
End If
finalResult = String.Format(value.ToString("0,0.00", System.Globalization.CultureInfo.InvariantCulture)) & " (ha)"
Console.WriteLine(finalResult)
End If
Console.Read()
Return

check which item is selected?

I try to check which data is selected in a DataGridViewComboBoxCell
Dim status As Double
For x As Integer = 0 To ATCGRID.Rows.Count - 1
If ATCGRID.Rows(x).Cells(2).Value = "Full" Then
status = 1
ElseIf ATCGRID.Rows(x).Cells(2).Value = "Empty" Then
status = 0
ElseIf ATCGRID.Rows(x).Cells(2).Value = "Half" Then
status = 0.5
End If
MessageBox.Show(status)
Next x
But Its getting error
Conversion from string "Full" to type "Double" is not valid.
How can I solve this?
Try to Parse your type database,
Dim strSQL As String = "INSERT INTO ATTENDANCE(EMP_ID,EMP_NAME,AT_DATE,AT_STATUS,AT_REMARK)VALUES(#EMP_ID,#EMP_NAME,#AT_DATE,#AT_STATUS,#AT_REMARK)"
query = New SqlCommand(strSQL, Conn)
query.Parameters.Add("#EMP_ID",SqlDbType.Decimal)
query.Parameters.Add("#EMP_ID").Value=id
query.Parameters.Add("#EMP_NAME",SqlDbType.Varchar,100)' Parse your length
query.Parameters.Add("#EMP_NAME").Value=name
query.Parameters.Add("#AT_DATE",SqlDbType.Date)
query.Parameters.Add("#AT_DATE").Value=atdate
query.Parameters.Add("#AT_STATUS",SqlDbType.Decimal)
query.Parameters.Add("#AT_STATUS").Value=status
query.Parameters.Add("#AT_REMARK",SqlDbType.Varchar,50)
query.Parameters.Add("#AT_REMARK").Value=name
The Value in the cells is a number, so it cannot be compared that way. Try this:
If ATCGRID.Rows(x).Cells(2).Value.ToString() = "FULL" Then

String conversion for SQL select statement

Using a SELECT statement I query a database and get back a result in the format: name1,name2,name3
Depending on the database entry this result could have any number of names: name1,name2...name(n)
I would like to use this data to query another database like so:
SELECT Name, SerialNo, Model FROM InstrumentTable where ID=1 and InstName IN name1,name2,name3
In order to do this I need to convert name1,name2,name3 to ('name1','name2','name3')
I have tried splitting the String into an array of Strings
Dim ref1s As String = cmdf1.ExecuteScalar()
Dim fields() As String = Nothing
fields = ref1s.Split(",")
and then concatenating them in an array
For i As Integer = 0 To fields.Count - 1
MsgBox(String.Concat("'", fields(i), "'"))
Next
but I haven't been able to figure out how to do it yet.
Adding the brackets at the start and end of the string shouldn't be a problem just adding the quotes to each name and separating them with a comma is the issue.
Can anyone help me with this?
You got a bit previous
For i As Integer = 0 To fields.Count - 1
fields[i] = String.Concat("'",fields[i],"'")
Next
Then
strValue = fields.Join(',')
user557425,
Something like this might point you in the right direction:
Dim lst As List(Of String)
For i As Integer = 0 to fields.Count - 1
if i = fields.Count - 1 Then
lst.Add(fields(i) & "'")
Else
lst.Add(fields(i) & "','")
End if
Next
Dim sqlSB As StringBuilder
sqlSB.Append("SELECT * FROM TABLE WHERE BLAH IN(")
For each s As String in lst
sqlSB.Append(s)
Next
'use the stringbuilder as command text in a SqlCommand...

Error on LINQ statement with enclosing variable

Trying to run the following LINQ statment:
Dim jobId As Integer = CInt(payment.ForJob)
Dim currentPaid = From a In db.Payments
Where a.ForJob = jobId
Select a.Amount
Get the following error on a.Amount though:
Range variable 'Amount' hides a variable in an enclosing block or a range variable previously defined in the query expression
Function RecordPaymentForJob(payment As Payment) As ActionResult
If ModelState.IsValid Then
Dim jobId As Integer = CInt(payment.ForJob)
Dim new currentPaid = From a In db.Payments
Where a.ForJob = jobId
Select a.Amount
Dim totalPaid As Double = currentPaid.Sum()
If (totalPaid + payment.Amount) > (db.Jobs.Find(payment.ForJob).JobAmount * -1) Then
db.Jobs.Find(payment.ForJob).JobStatus = "Paid"
Else
db.Jobs.Find(payment.ForJob).JobStatus = "Part Paid"
End If
Dim Id As Integer = payment.CustomerId
Dim amount As Double = db.Customers.Find(Id).AccBalance
amount += payment.Amount
db.Customers.Find(Id).AccBalance = amount
db.Payments.Add(payment)
db.SaveChanges()
Return Redirect("/Payment/PaymentSuccessful")
End If
Return View(payment)
End Function
I suspect this is the problem:
Dim amount As Double = db.Customers.Find(Id).AccBalance
I don't know VB very well, but I suspect the scope of this variable is the scope of the whole block, including that LINQ statement. In C# at least, that wouldn't be a problem... but the Select clause in VB works somewhat differently, I believe.
One alternative would be to compute the sum directly:
Dim totalPaid = db.Payments.Where(Function(a) a.ForJob = jobId).
Sum(Function(a) a.Amount)
My VB is pretty poor, but I think that should work.