How to merge DataRow() - vb.net

I have a DataTable (dt) which I need to filter under certain conditions I can only use 'Select'. I wrote code that work, but I want do it better:
Dim result As DataTable = dt.Clone
Dim r1 As DataRow() = Nothing
Dim r2 As DataRow() = Nothing
Dim r3 As DataRow() = Nothing
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
r1 = dt.Select("A < " & Quote(Date.UtcNow) & " AND B IS NULL")
r2 = dt.Select("B > " & Quote(Date.UtcNow) & " AND A IS NULL")
r3 = dt.Select("A < " & Quote(Date.UtcNow) & " AND B > " & Quote(Date.UtcNow))
End If
For i As Integer = 0 To r1.Length -1
result.ImportRow(r1(i))
Next
For i As Integer = 0 To r2.Length -1
result.ImportRow(r2(i))
Next
For i As Integer = 0 To r3.Length -1
result.ImportRow(r3(i))
Next
I cant find any solution to save result dt.Select to one DataRow() object and then do just one For loop. I am asking for suggestions,
Thanks!

In the morning I woke up with a fresh head and something that should have been obvious was a terrible time for me yesterday - OR - it settled the matter + CopyToDataTable()
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
dt = dt.Select("(A < " & Quote(Date.UtcNow) & " AND B IS NULL) OR (B > " & Quote(Date.UtcNow) & " AND A IS NULL) OR (A < " & Quote(Date.UtcNow) & " AND B > " & Quote(Date.UtcNow) & ")").CopyToDataTable()
End If
Return dt
Thank you for your time and especially jmcilhinney

Related

Visual Basic: how can I display certain values from a group of characters

Here we are finding the eight adjacent numbers that have the highest sum and displaying that sum. We also need to have it display the eight adjacent numbers that add up to this value. I am stuck on how to display these values. My code for what I have so far is below:
Dim chars As Char() = "73167176531330624919225119674426574742355349194934" &
"96983520312774506326239578318016984801869478851843" &
"85861560789112949495459501737958331952853208805511" &
"12540698747158523863050715693290963295227443043557" &
"66896648950445244523161731856403098711121722383113" &
"62229893423380308135336276614282806444486645238749" &
"30358907296290491560440772390713810515859307960866" &
"70172427121883998797908792274921901699720888093776" &
"65727333001053367881220235421809751254540594752243" &
"52584907711670556013604839586446706324415722155397" &
"53697817977846174064955149290862569321978468622482" &
"83972241375657056057490261407972968652414535100474" &
"82166370484403199890008895243450658541227588666881" &
"16427171479924442928230863465674813919123162824586" &
"17866458359124566529476545682848912883142607690042" &
"24219022671055626321111109370544217506941658960408" &
"07198403850962455444362981230987879927244284909188" &
"84580156166097919133875499200524063689912560717606" &
"05886116467109405077541002256983155200055935729725" &
"71636269561882670428252483600823257530420752963450"
Dim index As String = 0
Dim x = 0
Dim values = Array.ConvertAll(chars, Function(c) CInt(c.ToString()))
Dim maxSum = 0
For i = 0 To values.Length - 8
Dim sum = values(i)
For x = i + 1 To i + 7
sum += values(x)
index = i
Next
If sum > maxSum Then
maxSum = sum
End If
Next
Console.WriteLine(index)
Console.WriteLine(maxSum)
Console.Read()
End Sub
Here's my take on it using two different approaches. The first is a more traditional approach, while the second utilizes LINQ:
Sub Main()
Dim chunkSize As Integer = 8
Dim source As String =
"73167176531330624919225119674426574742355349194934" &
"96983520312774506326239578318016984801869478851843" &
"85861560789112949495459501737958331952853208805511" &
"12540698747158523863050715693290963295227443043557" &
"66896648950445244523161731856403098711121722383113" &
"62229893423380308135336276614282806444486645238749" &
"30358907296290491560440772390713810515859307960866" &
"70172427121883998797908792274921901699720888093776" &
"65727333001053367881220235421809751254540594752243" &
"52584907711670556013604839586446706324415722155397" &
"53697817977846174064955149290862569321978468622482" &
"83972241375657056057490261407972968652414535100474" &
"82166370484403199890008895243450658541227588666881" &
"16427171479924442928230863465674813919123162824586" &
"17866458359124566529476545682848912883142607690042" &
"24219022671055626321111109370544217506941658960408" &
"07198403850962455444362981230987879927244284909188" &
"84580156166097919133875499200524063689912560717606" &
"05886116467109405077541002256983155200055935729725" &
"71636269561882670428252483600823257530420752963450"
Dim strChunk As String
Dim strMaxChunk As String = ""
Dim curSum, MaxSum As Integer
Dim values() As Integer
For i As Integer = 0 To source.Length - chunkSize
strChunk = source.Substring(i, chunkSize)
values = Array.ConvertAll(strChunk.ToCharArray, Function(c) CInt(c.ToString()))
curSum = values.Sum
If curSum > MaxSum Then
MaxSum = curSum
strMaxChunk = strChunk
End If
Next
Console.WriteLine("Traditional")
Console.WriteLine("Max Sum = " & MaxSum & " from " & strMaxChunk)
Dim sums = From chunk In Enumerable.Range(0, source.Length - chunkSize).Select(Function(x) source.Substring(x, chunkSize))
Select chunk, sum = Array.ConvertAll(chunk.ToCharArray, Function(y) CInt(CStr(y))).Sum
Order By sum Descending
Dim linqResult = sums.First
Console.WriteLine("Linq")
Console.WriteLine("Max Sum = " & linqResult.sum & " from " & linqResult.chunk)
Console.ReadLine()
End Sub

Is there a faster way to retrieve data from a table?

I have used this loop to display Data that graph using the Google Chart
The problem is that the graph contains a lot of data and it takes a long time to be made loaning
The question is whether there is a faster way to pass the data base?
dRow As Data.DataRow In xdata.Rows
If j = 0 Then
TempDate = Format(CDate(dRow.Item(0)), "dd/MM/yyyy")
MyXML += "[new Date(" & TempDate.Year & "," & TempDate.Month - 1 & ")"
j += 1
Else
TempDate = Format(CDate(dRow.Item(0)), "dd/MM/yyyy")
MyXML += ",[new Date(" & TempDate.Year & "," & TempDate.Month - 1 & ")"
j += 1
End If
For colIdx As Byte = 1 To xdata.Columns.Count - 1
If colIdx > 0 Then
If (dRow.Item(colIdx)).ToString <> Nothing Then
MyXML += "," & (dRow.Item(colIdx)).ToString
Else
MyXML += "," & "0"
End If
End If
`
You should be using a StringBuilder if you are going to be concatenating hundreds of strings. .NET strings are immutable which means each time they change, a new object has to be created.
Dim sb As New StringBuilder
For dRow As Data.DataRow In xdata.Rows
If j = 0 Then
TempDate = Format(CDate(dRow.Item(0)), "dd/MM/yyyy")
sb.Append("[new Date(" & TempDate.Year & "," & TempDate.Month - 1 & ")")
j += 1
Else
TempDate = Format(CDate(dRow.Item(0)), "dd/MM/yyyy")
sb.Append(",[new Date(" & TempDate.Year & "," & TempDate.Month - 1 & ")")
j += 1
End If
For colIdx As Byte = 1 To xdata.Columns.Count - 1
If colIdx > 0 Then
If (dRow.Item(colIdx)).ToString <> Nothing Then
sb.Append("," & (dRow.Item(colIdx)).ToString)
Else
sb.Append("," & "0")
End If
End If
Next
Next
And when you're done parsing the data:
Return sb.ToString

How to check whether a string value is present in a DataGridView

Im working on a code that has a TextBox, A Button and a Datagrid view.
I want to Display "Data Not Exist" when a value in TextBox is not present on the DataGridView when i press the button.
This is my code so far
If DataGridView1.Rows.Contains(TextBox1.Text) = False Then
MessageBox.Show("Data Not Exist!")
End If
You need to loop through all rows and columns
Dim isFound As Boolean = False
For Each row As GridViewRow In DataGridView1.Rows
for i As Integer = 0 to DataGridView1.Columns.Count -1
If row.Cells[i].Text = TextBox1.text Then
isFound = True
exit for
End If
Next
Next
If (isFound) Then
MessageBox.Show("Data Exists!")
Else
MessageBox.Show("Data Not Exists!")
EndIf
You can do it easily with either using a LINQ or a ForLoop
This code will search all matches it will find across the DataGridView and will prompt in which Row and Column it sees the match.
With a ForLoop, you need to run a loop for Column and for the Row.
Private Sub SearchUsingForLoop()
Dim resultString As String = Nothing
For x = 0 To DataGridView1.ColumnCount - 1
For y = 0 To DataGridView1.RowCount - 1
If DataGridView1.Item(x, y).Value.ToString.ToUpper = txtSearch.Text.ToUpper Then
resultString &= " - Column " & x + 1 & " Row " & y + 1 & vbCrLf
End If
Next
Next
If resultString <> Nothing Then
resultString = txtSearch.Text & " found in : " & vbCrLf & resultString
Else
resultString = "Data does not exist."
End If
MsgBox(resultString)
End Sub
Do remember that index of DatagridViewRow and DatagridViewColumn starts with 0.
Another way of doing this is by LINQ:
Private Sub SearchUsingLINQ()
Dim resultSet = From dgRow As DataGridViewRow In Me.DataGridView1.Rows, _
dgCell As DataGridViewCell In dgRow.Cells _
Where dgCell.Value.ToString.ToUpper = txtSearch.Text.ToUpper _
Select dgCell
Dim resultString As String = Nothing
If resultSet.Count > 0 Then
resultString = txtSearch.Text & " found in :" & vbCrLf
For Each dgCells In resultSet
resultString &= " - Column " & dgCells.ColumnIndex + 1 & " Row " & dgCells.RowIndex + 1 & vbCrLf
Next
End If
If resultString <> Nothing Then
MsgBox(resultString)
Else
MsgBox("Data does not exist.")
End If
End Sub
Feel free to use any of those. But I suggest you to study iterating a DataGridView first.

string format using with increment

i have a ticket_no field which has a format of "storecode - datetoday - n" what i'm trying to is when as long as the date is today the "n" will just increment but if the date changes the "n" will reset to 1.
TMP_SQL = "select max(ticket_no) from tbl_main where store_id = '" + frm_store.store_code + "'"
Dim OBJCMD As New SqlCommand(TMP_SQL, OBJCON)
OBJREADER = OBJCMD.ExecuteReader()
Dim ydate As String
ydate = Now.ToString("MMddyy")
With OBJREADER
.Read()
Dim x As string
Dim str As String
If IsDBNull(OBJREADER(0)) = False Then
str = OBJREADER(0)
x = Int32.Parse(OBJREADER(0).ToString().Split("-")(1))
If x <> ydate Then
tmp = 0
tmp = Int32.Parse(OBJREADER(0).ToString().Split("-")(2)) + 1
Else
tmp = Int32.Parse(OBJREADER(0).ToString().Split("-")(2)) + 1
End If
End If
End With
txtTicketno.Text = frm_store.store_code & "-" & Now.ToString("MMddyy") & "-" & tmp

Search between two dates w/ datarows in vb 2010

I am trying to search between two dates in a bound source (SQL table) in VB 2010, using data rows. Since 'between' in unsupported with the data rows function, I used < and >.
So I run this code and the output is 900+ entries when the actual number of entries is 8. After hitting my button a second time without changing anything, the correct number of entries appears.
Private Sub cmdSearch_Click(sender As System.Object, e As System.EventArgs) _
Handles cmdSearch.Click
Dim Expression As String
Dim OrderStr As String = "Area"
Dim DateStr As String
Dim StartDate As String
Dim EndDate As String
Dim Shift As String = ""
Dim Area As String = ""
Dim Product As String
If (DtpStartDate.Value = Nothing Or DtpEndDate.Value = Nothing) Then
MsgBox("Please input a start and end date.")
Exit Sub
End If
If (radShiftAllSearch.Checked <> True _
And radShiftOneSearch.Checked <> True
And radShiftTwoSearch.Checked <> True _
And radShiftThreeSearch.Checked <> True) Then
MsgBox("Please select a shift to search for.")
Exit Sub
End If
Select Case True
Case radShiftOneSearch.Checked
Shift = " AND [Shift] = '1'"
Case radShiftTwoSearch.Checked
Shift = " AND [Shift] = '2'"
Case radShiftThreeSearch.Checked
Shift = " AND [Shift] = '3'"
Case radShiftAllSearch.Checked
Shift = " AND ([Shift] = '1' OR [Shift] = '2' OR [Shift] = '3')"
End Select
**StartDate = DtpStartDate.Value.Subtract(oneday)
EndDate = DtpEndDate.Value.Add(oneday)
'StartDate = Format(DtpStartDate.Value.Subtract(oneday), "M/dd/yyyy")
'EndDate = Format(DtpEndDate.Value.Add(oneday), "M/dd/yyyy")
DateStr = "[Dates] > '" & StartDate & "' AND [Dates] < '" & EndDate & "'"**
If (txtProductSearch.Text = "") Then
Product = ""
Else
Product = "AND [Product] LIKE '" & txtProductSearch.Text & "'"
End If
For h As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim XDRV As DataRowView = CType(CheckedListBox1.CheckedItems(h), DataRowView)
Dim XDR As DataRow = XDRV.Row
Dim XDisplayMember As String = XDR(CheckedListBox1.DisplayMember).ToString()
If (Area = "") Then
Area = Area & " AND ([Area] LIKE '" & XDisplayMember & "'"
Else
Area = Area & " OR [Area] LIKE '" & XDisplayMember & "'"
End If
Next
If (Area <> "") Then
Area = Area & ")"
End If
Expression = DateStr & Product & Shift & Area
TextBox4.Text = Expression
Dim SearchRows() As DataRow = _
ProductionDataSet.Tables("Production_Daily").Select(Expression, OrderStr)
'foundcount = SearchRows.Count - 1
DataGridView1.DataSource = SearchRows
DataGridView1.Show()
End Sub
Thanks