variable to a query - vb.net

I got this code:
...
Dim contP as String ="0"
Dim LeftJIF as String =""
sqlquery =("select CLas1, CLas2, CLas3"+ContP+"
from CLas" + LeftJIF )
Using connection As SqlConnection = New SqlConnection("server=" & srvSQL & ";database=" & bdSQL & ";uid=" & usrSQL & ";password=" & pswSQL & ";")
connection.Open()
Using com As SqlCommand = New SqlCommand(sqlquery, connection)
Dim rs As SqlDataReader = com.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(rs)
''Here I'm trying to do what's below.
Call clCreateCSV.CreateCSVFile(dt, strFileName)
End Using
connection.Close()
End Using
So, for each result on the query I need to fill the variable ContP with data coming from a left join. IF the field "CLas3" from each one is "472" or "477" it will assign a table field and the left join acordingly
I was thinking in something like this just following dt.Load(rs)
For Each dr As DataRow In dt.Rows
If dt.Rows(0).Item("CLas3") = "472" Then
ContP = "clients.client3"
leftJoinsif = "left join InvoiceS on CLas4 = InvoiceS.invoice4
" + "left join clients on InvoiceS.invoice5 = clients.client1"
ElseIf dt.Rows(0).Item("CLas3") = "477" Then
ContP = "providers.provider3"
leftJoinsif = "left join InvoiceV on CLas4 = InvoiceV.invoice4
" + "left join providers on InvoiceV.invoice5 = providers.provider1"
Else
contP = ""
leftJoinsif = ""
End If
Next
The tables look like this, just in case is needed.
CLas
::::::::::::::::::::::::::::::::::::::::
CLas1 | Clas2 | CLas3 | Clas4
10 R 472 I1
10 S 600 I1
10 N 129
20 S 700 I2
20 R 472 I2
...
InvoiceS
::::::::::::::::::::::::::::::::::::::::
invoice1 | invoice2 | invoice3 | invoice4 | invoice5
001 x y I1 000001
002 x y I2 000002
...
clients
::::::::::::::::::::::::::::::::::::::::
client1 | client2 | client3
000001 name V
000002 name C
...
So, after all the query should result in something like:
10,R,472,V
10,S,600,
10,N,129,
20,S,700,
20,R,472,C
All in all, it's failing, not retrieving anything. Tested the query separately on a sql server and seems to be working. I'm not sure if there is an easier way to do this or if I can operate with the dt rows on that state(Still not quite understand it yet)
Thanks in advance.

Related

Faster way to loop through DataTable elements

Description of the current situation:
I have an excel file of approximately 315 columns and 4000 rows. The file contains the answers to a 300-question questionnaire. The data format is as follows:
(Headers) A | B | C | D | E | F | Q.1 | Q.2 | ... | Q.300 |
(FirstRow) Info of first participant | AnswerCode for every Q |
The columns A to F contain contain info on every participant, while the columns Q.1 to Q.300 contain the respective answer code to each question. After storing the file as a large DataTable:
I need to load all 4000 rows on an existing database table, but before I do that I must edit the data format. The end result must become:
ParticipantCode | QuestionCode | AnswerCode | DateOfRegistration
00001 | 0001 | 1234567 | yyyy-MM-dd HH:mm:ss
... | ... | ... | ...
00001 | 0300 | 1234567 | yyyy-MM-dd HH:mm:ss
00002 | 0001 | 1234567 | yyyy-MM-dd HH:mm:ss
... | ... | ... | ...
04000 | 0300 | 1234567 | yyyy-MM-dd HH:mm:ss
So every row of the original ExcelDataTable is transformed into 300 rows in the FinalDataTable. In this way, the FinalDataTable will have about 1.2 million rows.
What Have I implemented so far:
Private Function MyFunction()
For Each ExcelRow As DataRow In ExcelDataTable.Rows
For Each ExcelColumn As DataColumn In ExcelDataTable.Columns
QuestionCodeFound = False
ExcelColumnNameRaw = ExcelColumn.ColumnName.ToString.Trim
If ExcelColumnNameRaw.StartsWith("Q") Then
' Correct the headers
ExcelColumnSplit = ExcelColumnNameRaw.Split("#")
ExcelColumnName = String.Concat(ExcelColumnSplit(0), ExcelColumnSplit(1))
SelectedRowFromDT = QuestionCodeAndQuestionIDDataTable.Select("QuestionID = '" + ExcelColumnName + "'")
' Search for "_", because some questions are different
If SelectedRowFromDT.Length > 0 Then
QuestionCodeFound = True
Else
Dim ExcelColumnSplitForMult As String()
ExcelColumnSplitForMult = ExcelColumnName.Split("_")
SelectedRowFromDT = QuestionCodeAndQuestionIDDataTable.Select("QuestionID = '" + ExcelColumnSplitForMult(0).ToString + "'")
If SelectedRowFromDT.Length > 0 Then
QuestionCodeFound = True
End If
End If
If QuestionCodeFound Then
Dim QuestionCode As String
Dim QuestionTypeDataTable As DataTable
Dim QuestionType As String
' Get the Question Type from the respective table
QuestionType = String.Empty
QuestionCode = SelectedRowFromDT(0).Item("QuestionCode").ToString
QuestionTypeDataTable = SearchInSql(My.Settings.ConnectionString, SQLString)
If QuestionTypeDataTable.Rows.Count > 0 Then
QuestionType = QuestionTypeDataTable.Rows(0).Item(0).ToString.Trim
End If
' Fix the Date Format
DateRaw = ExcelRow.Item(1).ToString
DateSplit = DateRaw.Split("/")
If DateSplit(0).Length = 1 Then
DateSplit(0) = String.Concat("0", DateSplit(0))
End If
If DateSplit(1).Length = 1 Then
DateSplit(1) = String.Concat("0", DateSplit(1))
End If
DateText = String.Concat(DateSplit(0), "/", DateSplit(1), "/", DateSplit(2))
DateRegistration = DateTime.ParseExact(DateText, "MM/dd/yyyy", CultureInfo.InvariantCulture)
DateRegistrationReformed = DateRegistration.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
DateRegFinal = DateTime.ParseExact((DateRegistrationReformed + " " + "10:00:00").ToString, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)
Dim AnswerValue As String
Dim AnswerCode As String
Dim AnswerCodeDataTable As DataTable
Dim QuestionWasAnswer As String
Dim AnswerValueRow() As DataRow = ExcelDataTable.Select("ParticipantCode = '" + ExcelRow.Item(2).ToString + "'")
AnswerCodeDataTable = New DataTable
AnswerValue = ""
QuestionWasAnswer = "0"
' Complete "QuestionWasAnswer" field for all questions and retrieve the AnswerCode for the answer given by each participant
If AnswerValueRow.Length > 0 And AnswerValueRow(0).Item(ExcelColumnNameRaw).GetType IsNot GetType(DBNull) Then
If Not (QuestionType.Equals("02") Or QuestionType.Equals("03")) Then
AnswerValue = AnswerValueRow(0).Item(ExcelColumnNameRaw)
QuestionWasAnswer = "1"
ElseIf QuestionType.Equals("02") Or QuestionType.Equals("03") Then
Dim ExcelColumnSplitForMultSecond As String()
Dim MultAnswerValue As String
ExcelColumnSplitForMultSecond = ExcelColumnName.Split("_")
MultAnswerValue = AnswerValueRow(0).Item(ExcelColumnNameRaw).ToString.Trim
AnswerValue = ExcelColumnSplitForMultSecond(1).ToString
If MultAnswerValue.Equals("1") Then
QuestionWasAnswer = "1"
ElseIf MultAnswerValue.Equals("2") Then
QuestionWasAnswer = "2"
End If
End If
' Search in the Answers table for the existing AnswerCode
SQLString = String.Format("SELECT Answers.AnswerCode
FROM Answers
WHERE Answers.QuestionCode = '{0}'
AND (Answers.AnswerNumber = '{1}' OR Answers.Answer = '{1}')", QuestionCode, AnswerValue)
AnswerCodeDataTable = SearchInSql(My.Settings.ConnectionString, SQLString)
If AnswerCodeDataTable.Rows.Count > 0 Then
AnswerCode = AnswerCodeDataTable.Rows(0).Item(0).ToString
FormattedDataTable.Rows.Add(ParticipantAnswerCode, ExcelRow.Item(2), QuestionCode, AnswerCode, QuestionWasAnswer, DateRegFinal)
ParticipantAnswerCode = Convert.ToInt32(ParticipantAnswerCode + 1).ToString.PadLeft(ParticipantAnswerCodeFieldLength, "0")
Else
' If a given answer does not exist, save it in the respective table and then try again
Dim AnswerCodeLength = GetLengthFromSqlDataBase(My.Settings.ConnectionString, "Answers", "AnswerCode")
Dim NextAnswerCode = CalculateNextAnswerCode(AnswerCodeLength)
Dim NestAnswerNumber = CalculateNextAnswerNumber(QuestionCode)
SaveNewAnswer(NextAnswerCode, QuestionCode, NestAnswerNumber, AnswerValue)
SQLString = String.Format("SELECT Answers.AnswerCode
FROM Answers
WHERE Answers.QuestionCode = '{0}'
AND Answers.Answer = '{1}'", QuestionCode, AnswerValue)
AnswerCodeDataTable = SearchInSql(My.Settings.ConnectionString, SQLString)
If AnswerCodeDataTable.Rows.Count > 0 Then
AnswerCode = AnswerCodeDataTable.Rows(0).Item(0).ToString
FormattedDataTable.Rows.Add(ParticipantAnswerCode, ExcelRow.Item(2), QuestionCode, AnswerCode, QuestionWasAnswer, DateRegFinal)
ParticipantAnswerCode = Convert.ToInt32(ParticipantAnswerCode + 1).ToString.PadLeft(ParticipantAnswerCodeFieldLength, "0")
End If
End If
End If
End If
End If
Next
Next
Return FormattedDataTable
End Function
After that, I bulk insert the FinalDataTable on the DB.
The problem I am facing:
Using the current program I built, every row in the ExcelDataTable takes about 40 seconds to transform into 300 rows in the FinalDataTable. If I try to load all 4000 rows, it will take more than 40 hours to transform the entire datatable. I need to find a faster way to do this.
As mentioned, there isn't much to go off of on this with what has been provided.
I'm sure there are more helpful fixes to consider but I wanted to put my two cents in about the For Loops.
I recommend switching the
For Each
statements with
For i as integer = 0 to ExcelDataTable.Rows.Count - 1
I've read that For Each is not as performance-friendly as it gathers each "row" as a collection, therefore increasing the overhead per loop.
Here is a SO post about this subject:
Major difference between 'for each' and 'for' loop in .NET
Not sure if that will make a difference for you but thought I would recommend it anyway.

datatable sum column and concatenate rows using LINQ and group by on multiple columns

I Have a datatable with following records
ID NAME VALUE CONTENT
1 AAA 10 SYS, LKE
2 BBB 20 NOM
1 AAA 15 BST
3 CCC 30 DSR
2 BBB 05 EFG
I want to write a VB.NET/LINQ query to have a output like below table: -
ID NAME SUM CONTENT (as CSV)
1 AAA 25 SYS, LKE, BST
2 BBB 25 NOM, EFG
3 CCC 30 DSR
Please provide me LINQ query to get the desired result. Thanks.
I have tried concatenation using below query
Dim grouped = From row In dtTgt.AsEnumerable() _
Group row By New With {row.Field(Of Int16)("ID"), row.Field(Of String)("Name")} _
Into grp() _
Select ID, Name, CONTENT= String.Join(",", From i In grp Select i.Field(Of String)("CONTENT"))
This query will give you the expected output:-
Dim result = From row In dt.AsEnumerable()
Group row By _group = New With {Key .Id = row.Field(Of Integer)("Id"),
Key .Name = row.Field(Of String)("Name")} Into g = Group
Select New With {Key .Id = _group.Id, Key .Name = _group.Name,
Key .Sum = g.Sum(Function(x) x.Field(Of Integer)("Value")),
Key .Content = String.Join(",", g.Select(Function(x) x.Field(Of String)("Content")))}
Thanks for your answers.
However, I have managed to get the desired result using simple code (Without LINQ): -
Dim dt2 As New DataTable
dt2 = dt.Clone()
For Each dRow As DataRow In dt.Rows
Dim iID As Integer = dRow("ID")
Dim sName As String = dRow("Name")
Dim sContt As String = dRow("Content")
Dim iValue As Integer = dRow("Value")
Dim rwTgt() As DataRow = dt2.Select("ID=" & iID)
If rwTgt.Length > 0 Then
rwTgt(0)("Value") += iValue
rwTgt(0)("Content") += ", " & sContt
Else
rw = dt2.NewRow()
rw("ID") = iID
rw("Name") = sName
rw("Value") = iValue
rw("Content") = sContt
dt2.Rows.Add(rw)
End If
Next

how to use an in clause to check if a column is a certain string or not when referencing 3 tables

I have this SQL statement and it joining 2 tables...
SELECT TRIDENT.Maintenance.RCFAs.*, TRIDENT.Maintenance.Equipment.EquipmentName
FROM TRIDENT.Maintenance.RCFAs
LEFT JOIN TRIDENT.Maintenance.Equipment
ON TRIDENT.Maintenance.Equipment.EquipmentId = TRIDENT.Maintenance.RCFAs.EquipmentId
WHERE 1 = 1
Now I have to reference a third table because I have a dropdown by the name of components that we will use to lookup stuff on the table named TRIDENT.Maintenance.RCFAXrefComponents. So if "bolts" is selected from the dropdown it will look up the YEAR and RCFAID which makes a unqiue key for both RCFAXrefComponents and RCFAs and checks if there are any rows in RCFAs that had "bolts" in the component column when looking up that YEAR and RCFAId. A coworker suggested I use an IN clause to check if the YEAR and RCFAId is in that RCFAXrefComponents. He said it might be tricky, but I'm a little lost on how to do this.
Below is the RCFAs table that I want to grab the YEAR and RCFAId values together and lookup on the other to see if that bolt is also there. Then it should bring up the line item on RCFAs table to output to user
this is RCFAXrefComponents table below
Public Shared Function GetRCFAList(rcfaNumber As Integer?, description As String,
failureType As String, equipmentDescription As String, componentSelection As String) As List(Of RCFA)
Dim sql = "SELECT r.*, e.EquipmentName FROM TRIDENT.Maintenance.RCFAs AS r LEFT JOIN TRIDENT.Maintenance.Equipment AS e ON e.EquipmentId = r.EquipmentId JOIN TRIDENT. Maintenance.RCFAXrefComponents AS c ON c.Year = r.Year AND c.RCFAId = r.RCFAId WHERE"
If failureType <> "" Then
sql += " AND RCFAs.FailureType = '" & failureType.ToUpper & "'"
End If
If description <> "" Then
sql += " AND RCFAs.ShortDesc LIKE '%" & description.ToUpper & "%'"
End If
If equipmentDescription <> "" Then
sql += " AND Equipment.EquipmentName LIKE '%" & equipmentDescription.ToUpper & "%'"
End If
If componentSelection <> "" Then
sql += " c.ComponentId = '%" & componentSelection.ToUpper & "%'"
End If
Dim dbConn As New Trident.Core.DBConnection
Dim ds = dbConn.FillDataSet(sql)
Dim tmpList As New List(Of RCFA)
For Each dr As DataRow In ds.Tables(0).Rows
tmpList.Add(New RCFA(New Trident.Objects.Maintenance.RCFA.RCFA(dr)))
Next
Return tmpList
End Function
Just use a simple JOIN with the RFCAXrefComponents table, and a WHERE clause that filters the component ID.
SELECT r.*, e.EquipmentName
FROM TRIDENT.Maintenance.RCFAs AS r
LEFT JOIN TRIDENT.Maintenance.Equipment AS e
ON e.EquipmentId = r.EquipmentId
JOIN TRIDENT.Maintenance.RCFAXrefComponents AS c
ON c.Year = r.Year
AND c.RCFAId = r.RCFAId
WHERE c.ComponentID = 'BOLTS'
I may be confused but it sounds like you need to use EXISTS.
SELECT r.*,
e.EquipmentName
FROM TRIDENT.Maintenance.RCFAs r
LEFT JOIN TRIDENT.Maintenance.Equipment e ON e.EquipmentId = r.EquipmentId
WHERE EXISTS ( SELECT 1
FROM TRIDENT.Maintenance.RCFAXrefComponents c
WHERE c.Year = r.Year
AND c.RCFAId = r.RCFAId
AND c.ComponentId LIKE '%BOLTS%' )
you may not need the c.ComponentId LIKE '%BOLTS%' you might just want c.ComponentId = 'BOLTS'

vb.net implict inner join syntax error (missing operator) in query expression

This is the code where I am getting exception message. However this code worked perfect in sql server 2005 but generating error in access.
This code working fine in sql server project but in access its generating exception as I mentioned..
Public Function CalculateFeeReciept(ByVal monthid As Integer) As DataTable
Dim cmd1 As New OleDbCommand("Select * from mstFeeHead", sqlcon)
Dim dtmstFeeHead As New DataTable 'dtmstFeeHead contains all the fee heads id's
Dim adp1 As New OleDbDataAdapter(cmd1)
adp1.Fill(dtmstFeeHead)
cmd1.Dispose()
Dim selectedmonth As Integer
Dim feeheadid As Integer
Dim arr(25) As Integer 'arr contains Fee head id's that should be paid in the selected month
If monthid = 13 Then
monthid = 1
ElseIf monthid = 14 Then
monthid = 2
ElseIf monthid = 15 Then
monthid = 3
End If
selectedmonth = monthid + 3
Dim m As Integer = 0
For j As Integer = 0 To dtmstFeeHead.Rows.Count - 1
feeheadid = Convert.ToInt32(dtmstFeeHead.Rows(j)(0))
If dtmstFeeHead.Rows(j)(selectedmonth) Then
arr(m) = feeheadid
m = m + 1
End If
Next
Dim cmd2 As New OleDbCommand("SELECT txnStudentFeeHead.FeeHeadID, mstFeeHead.FeeHeadName, mstFeePlan.Amount " & _
"FROM " & _
"txnStudentFeeHead " & _
"INNER JOIN " & _
"mstFeeHead " & _
"ON " & _
"txnStudentFeeHead.FeeHeadID = mstFeeHead.FeeHeadID " & _
"INNER JOIN " & _
"mstFeePlan " & _
"ON " & _
"mstFeeHead.FeeHeadID = mstFeePlan.FeeHeadID " & _
"WHERE " & _
"txnStudentFeeHead.StudentID = #StudentID) " & _
"AND " & _
"(mstFeePlan.SessionID = #SessionID) " & _
"AND " & _
"(mstFeePlan.ClassID = #ClassID) ", sqlcon)
cmd2.CommandType = CommandType.Text
cmd2.Parameters.Add("#StudentID", OleDbType.Integer).Value = StudentID()
cmd2.Parameters.Add("#ClassID", OleDbType.Integer).Value = Convert.ToInt32(cmbClass.SelectedValue)
cmd2.Parameters.Add("#SessionID", OleDbType.Integer).Value = Convert.ToInt32(cmbSession.SelectedValue)
Dim dt As New DataTable 'dt contains all the fee head id's that are alloted to the students
Dim adp As New OleDbDataAdapter(cmd2)
adp.Fill(dt)
cmd2.Dispose()
Dim dt2 As New DataTable 'dt2 contains all the fee head id's that are alloted to the student and that should be paid in that particular month
' dt2 contains the filtrate of dt and arr
dt2 = dt.Clone()
For i As Integer = 0 To arr.Length - 1
For j As Integer = 0 To dt.Rows.Count - 1
Dim dtrow As DataRow = dt2.NewRow()
If arr(i) = dt.Rows(j)(0) Then
dtrow(0) = arr(i)
dtrow(1) = dt.Rows(j)(1)
dtrow(2) = dt.Rows(j)(2)
dt2.Rows.Add(dtrow)
End If
Next
Next
cmd2 = New OleDbCommand("Select Sum(TotalFees) as TotalFees, Sum(LateFees) as TotalLateFees, Sum(OldBalance) as TotalOldBalance, Sum(Discount) as TotalDiscount, Sum(Scholarship) as TotalScholarship, Sum(Concession) as TotalConcession, Sum(AmountReceived) as TotalAmountReceived from txnFeePayment where SessionID=#SessionID and StudentID=#studentid and MonthID=#monthid Group by StudentId,MonthID", sqlcon)
cmd2.CommandType = CommandType.Text
cmd2.Parameters.Add("#studentid", OleDbType.Integer).Value = StudentID()
cmd2.Parameters.Add("#SessionID", OleDbType.Integer).Value = cmbSession.SelectedValue
cmd2.Parameters.Add("#monthid", OleDbType.Integer).Value = monthid
Dim dtStudentReciept As New DataTable 'dt contains all the fee head id's that are alloted to the students
adp = New OleDbDataAdapter(cmd2)
adp.Fill(dtStudentReciept)
cmd2.Dispose()
Dim dtrow1 As DataRow = dt2.NewRow()
If (dtStudentReciept.Rows.Count > 0) Then
dtrow1(0) = 0
dtrow1(1) = "Total Late Fees"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(1))
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Discount"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(3)) * -1
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Scholarship"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(4)) * -1
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Concession"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(5)) * -1
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Amount Received"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(6)) * -1
dt2.Rows.Add(dtrow1)
Dim totalamount As Integer = 0
For k As Integer = 0 To dt2.Rows.Count - 1
totalamount = totalamount + dt2.Rows(k)(2)
Next
'dtrow1 = dt2.NewRow()
'dtrow1(0) = totalamount
'dtrow1(1) = "Current Month Fee"
'dtrow1(2) = totalamount
'dt2.Rows.Add(dtrow1)
Else
Dim totalamount As Integer = 0
For k As Integer = 0 To dt2.Rows.Count - 1
totalamount = totalamount + dt2.Rows(k)(2)
Next
'dtrow1 = dt2.NewRow()
'dtrow1(0) = totalamount
'dtrow1(1) = "Current Month Fee"
'dtrow1(2) = totalamount
'dt2.Rows.Add(dtrow1)
End If
dgvDisplay.DataSource = dt2
For i As Integer = 0 To dgvDisplay.Columns.Count - 1
dgvDisplay.Columns.Item(i).SortMode = DataGridViewColumnSortMode.NotSortable
dgvDisplay.Columns(2).Width = 65
dgvDisplay.Columns(1).Width = 132
Next
dgvDisplay.Columns.Item(0).Visible = False
'txtTotalFees.Text = dt2.Rows(dt2.Rows.Count - 1)(0)
Return dt2
End Function
There are a couple of things wrong with your query.
You havent left any spaces once a line in code is finished and whole query may look like they are separate lines but it is a one long string without any spaces.
I have added spaces in the following piece of code at the end of each line.
("SELECT [txnStudentFeeHead].[FeeHeadID],[mstFeeHead].[FeeHeadName]," & _
"[mstFeePlan].[Amount] " & _
"FROM " & _
"[txnStudentFeeHead] " & _
"INNER JOIN " & _
"[mstFeeHead] " & _
You have put your variables in sqaure brackets [] , which means SQL Server will treat them as SQL Server Object(table name, Column Name) names and not as Variables. Remove the Square brackets.
"WHERE " & _
"([txnStudentFeeHead].[StudentID] = #StudentID) " & _
"AND" & _
"([mstFeePlan].[SessionID] = #SessionID) " & _
"AND" & _
"([mstFeePlan].[ClassID] = #ClassID) ", sqlcon)
Solved it myself by long time of effort and headache
Dim cmd2 As New OleDbCommand("SELECT txnStudentFeeHead.FeeHeadID, mstFeeHead.FeeHeadName, mstFeePlan.Amount, txnStudentFeeHead.StudentID, mstFeePlan.ClassID, mstFeePlan.SessionID FROM (txnStudentFeeHead INNER JOIN mstFeeHead ON txnStudentFeeHead.FeeHeadID = mstFeeHead.FeeHeadID) INNER JOIN mstFeePlan ON mstFeeHead.FeeHeadID = mstFeePlan.FeeHeadID WHERE (((txnStudentFeeHead.StudentID)=#StudentID) AND ((mstFeePlan.ClassID)=#ClassID) AND ((mstFeePlan.SessionID)=#SessionID))", sqlcon)
cmd2.CommandType = CommandType.Text
cmd2.Parameters.Add("#StudentID", OleDbType.Integer).Value = StudentID()
cmd2.Parameters.Add("#ClassID", OleDbType.Integer).Value = Convert.ToInt32(cmbClass.SelectedValue)
cmd2.Parameters.Add("#SessionID", OleDbType.Integer).Value = Convert.ToInt32(cmbSession.SelectedValue)
Dim dt As New DataTable 'dt contains all the fee head id's that are alloted to the students
Dim adp As New OleDbDataAdapter(cmd2)
adp.Fill(dt)
cmd2.Dispose()

How to merge cells and remove blank spaces in my DataGrid using proper loop

My title is still broad so i'll explain here further.
This is my current output using my code:
.
But I want to make it look like this..
As you can see on the pictures, i want to remove the blank spaces. Because if I selected MORE data, let's say I selected 7 more days, it will go DIAGONALLY not horizontally.
I think I have a problem regarding my loops. Hope you can help me trace because I've been stuck here for a week debugging. (nevermind my long query, i just want to post all my code. I've also added comments for easier debugging.)
Here's my code:
Private Sub LoadDateAndUser()
Dim SqlStr As String = ""
Dim sqlConn As New SqlConnection(DataSource.ConnectionString)
Dim sqlComm As New SqlCommand(SqlStr, sqlConn)
Dim sqlAdapter As New SqlDataAdapter(sqlComm)
Dim o_Dataset As New DataSet()
SqlStr = " SELECT convert(varchar(10), A.TransDate, 101) as TransDate,ADMMED.TransNum, ADMMED.AdministeredDate, D.Dosage [Dosage], ISNULL(C.GenericName, ' ') + ' (' + IsNull(B.ItemName,'') + ' ' + IsNull(B.ItemDesc,'') + ')' [Medication], ADMMED.UserID" & _
" FROM INVENTORY..tbInvStockCard as A" & _
" LEFT OUTER JOIN INVENTORY..tbInvMaster as B On A.ItemID = B.ItemID " & _
" LEFT OUTER JOIN Inventory.dbo.tbForGeneric as C On B.GenericID = C.GenericID" & _
" LEFT OUTER JOIN Station..tbNurse_AdministeredMedicines ADMMED on a.idnum= ADMMED.idnum " & _
" LEFT OUTER JOIN build_file.dbo.tbCoDosage as D on A.DosageID = D.DosageID" & _
" LEFT OUTER JOIN Station.dbo.tbNurseCommunicationFile as E on A.IdNum = E.IDnum and E.ReferenceNum = A.RefNum" & _
" WHERE A.IdNum = '" & Session.Item("IDNum") & "' and ( A.RevenueID = 'PH' or A.RevenueID = 'PC' ) " & _
" AND A.LocationID = '20' and Not IsNull(ADMMED.AdministeredDate, '') = ''" & _
" AND A.RefNum = ADMMED.ReferenceNum and ADMMED.ItemID = A.itemid" & _
" AND (B.ItemClassificationID = '1' or B.ItemClassificationID = '10' or B.ItemClassificationID = '11' or B.ItemClassificationID = '16' or B.ItemClassificationID = '2' or B.ItemClassificationID = '9')" & _
" order by TransDate desc,ADMMED.AdministeredDate desc"
sqlComm.CommandText = SqlStr
sqlAdapter.Fill(o_Dataset, "Table")
Dim o_Row As DataRow
Dim o_AdmDates As New Collection()
Dim s_FormattedLastAdmDate As String = ""
Dim s_FormattedAdmDate As String = ""
Dim o_DerivedTable As New DataTable()
With o_DerivedTable
.Columns.Add("TransDate")
.Columns.Add("Medication")
.Columns.Add("Dosage")
.Columns.Add("TransNum")
End With
'Select all unformatted administered dates from the query
Dim o_UnformattedAdmDates As DataRow() = o_Dataset.Tables(0).Select("", "AdministeredDate Desc")
'Extract distinct administered dates and change its format
For Each o_Row In o_UnformattedAdmDates
s_FormattedAdmDate = Format(CDate(o_Row.Item("AdministeredDate")), KC_Date_Format) 'eg. Jan 01 15
If s_FormattedLastAdmDate <> s_FormattedAdmDate Then
s_FormattedLastAdmDate = s_FormattedAdmDate
o_AdmDates.Add(s_FormattedLastAdmDate) 'add all formatted dates in o_AdmDates
End If
Next
'Add formatted administred dates to derived table
Dim o_Item As String
For Each o_Item In o_AdmDates
o_DerivedTable.Columns.Add(o_Item)
Next
'Loop through the administred date
Dim o_NewRow As DataRow
Dim o_NextRow As DataRow
Dim i_Ctr As Integer
Dim x_isNewRow As Boolean = True
Dim i_MaxRec As Integer
i_MaxRec = o_Dataset.Tables(0).Rows.Count - 1
For i_Ctr = 0 To i_MaxRec
o_Row = o_Dataset.Tables(0).Rows(i_Ctr)
If i_Ctr <> i_MaxRec Then
o_NextRow = o_Dataset.Tables(0).Rows(i_Ctr + 1)
End If
If x_isNewRow Then
o_NewRow = o_DerivedTable.NewRow()
End If
o_NewRow("TransDate") = o_Row("TransDate")
o_NewRow("Medication") = o_Row("Medication")
o_NewRow("Dosage") = o_Row("Dosage")
o_NewRow("TransNum") = o_Row("TransNum")
'Fill approriate result date column based on query
For Each o_Item In o_AdmDates
s_FormattedAdmDate = Format(CDate(o_Row.Item("AdministeredDate")), KC_Date_Format)
Dim AdmTim As DateTime = DateTime.Parse(o_Row("AdministeredDate"))
If s_FormattedAdmDate = o_Item Then
o_NewRow(s_FormattedAdmDate) = AdmTim.ToString("hh:mm tt") + " - " + o_Row("UserID")
End If
Next
If i_Ctr < i_MaxRec _
And Not o_NextRow Is Nothing _
And o_Row("TransDate") = o_NextRow("TransDate") _
And o_Row("Medication") = o_NextRow("Medication") _
And o_Row("Dosage") = o_NextRow("Dosage") _
And o_Row("AdministeredDate") = o_NextRow("AdministeredDate") Then
x_isNewRow = False
Else
o_DerivedTable.Rows.Add(o_NewRow)
x_isNewRow = True
End If
Next
'Bind derived table
dgSheet.DataSource = o_DerivedTable
dgSheet.DataBind()
If o_Dataset.Tables(0).Rows.Count > 0 Then
GroupGridView(dgSheet.Items, 0, 3)
Else
End If
End Sub
I think you must review your programming logic:
After that huge ugly SqlStr : you will have a DataSet, with a Table with all rows mixed !?
Let's try a pseudo-code:
I think is better to create in that DataSet, 2 Tables:<br>
**first** table with: id, DateOrder, Medication, Dosage <br>
and **second** table with: idDate, FirstTable.id, AdministeredDate
after that you know how many ADMMED.AdministeredDate.Count are, because you must know how manny columns you need to add
create a 3-rd table from iteration of first table, nested with second by ID.
Set as Datasource for DataGridView the Third DataTable.
So you have 2 datasets, and generate this one .. one to many ..
.. I have no time now, if you don't get the ideea .. forget it !