Can some please help- Previously I was storing this in database
File Name - Order.csv
File Arrival Time - 03:00
File Arrival End time - 04:00
But now I need to move this out from database and using MULTI-DIMENSIONAL ARRAY to store values and then iterate through them to check if files has arrived.
I have the code to check for file existance but im new to vb.net so don't now how to store this in multi-dimensional array and then iterate through it.
Please help.
if you really want to use arrays, you could try something like:
Dim data(,,) As String
ReDim data(10, 10, 10) ' three dimensions
For i As Integer = 0 To data.GetUpperBound(0)
For j As Integer = 0 To data.GetUpperBound(1)
For k As Integer = 0 To data.GetUpperBound(2)
' do your stuff here
Next
Next
Next
But, why not use object and list instead? something like:
Public Class MyFile
Property Name As String
Property ArrivalTime As DateTime
Property EndTime As DateTime
End Class
' then store the data in a list(of MyFile):
Public Class Test
Sub LoadingData()
Dim myData = New List(Of MyFile)
Using conn As New SqlClient.SqlConnection("your connection string here")
Using cmd As New SqlClient.SqlCommand()
cmd.Connection = conn
cmd.CommandText = "SELECT top 100 Name, ArrivalTime, EndTime FROM yourTable"
conn.Open()
Using rdr As SqlClient.SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim namePos = rdr.GetOrdinal("Name")
Dim timePos = rdr.GetOrdinal("Time")
Dim endTimePos = rdr.GetOrdinal("EndTime")
While rdr.Read()
myData.Add(New MyFile With {.Name = rdr.GetString(namePos),
.ArrivalTime = rdr.GetDateTime(timePos),
.EndTime = rdr.GetDateTime(endTimePos)})
End While
End Using
End Using
End Using
For Each item In myData
' Do whatever you like with each item
Console.WriteLine(String.Format("Name: {0}, Arrival Time: {1:yyyy-MM-dd HH:mm:ss}, End Time: {2:yyyy-MM-dd HH:mm:ss}",
item.Name,
item.ArrivalTime,
item.EndTime))
Next
End Sub
End Class
-- just a quick sample, not tested, you may tweak according to your needs)...
Related
I have data on my MS.Excel spreadsheet which contain different column (Sn , Amount and tech id). I am trying to put all the data of tech id on tech id in array like :-
mydata = [43219 , 43220 , 43221 , 43222 ,43223 ,43224 , 43225 ]
My code of only one main processing function:-
Importing :-
Imports System.IO
Imports System.Data.OleDb
main processing function:-
Dim conString1 As String
Dim Mydata(200) As Integer
Dim connection As OleDbConnection
Dim adapter As OleDbDataAdapter
Private Sub LoadData(conStr As String)
con = New OleDbConnection(conStr)
Dim query As String = "SELECT * FROM [Sheet0$]"
adapter = New oleDbDataAdapter(query, connection)
'Putting data indide array
'For intCount = 0 To lengthofcolumn
'Mydata(intCount) = ?
'Next intCount
Debug.Print(adapter)
End Sub
Calling :-
conString1 = String.Format("Provider = Microsoft.Jet.OLEDB.4.0;Data Source = '{0}'; Extended Properties = Excel 8.0", 'F:\MicroTest\data\log.xlsx)')
LoadData(conString1)
I am a student , I am learning so please help ,I did't find this solution , Mostly I found solution of viewing excel data in datagrid
My test data was in B2:B8.
You will need to add the Reference: Microsoft Excel 14.0 Object Library
Dim oExcel As New Microsoft.Office.Interop.Excel.Application
oExcel.Workbooks.Open("C:\TEMP\test_data.xlsx")
Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet = oExcel.Sheets(1)
' I would use list instead of an array.
Dim oTest As New List(Of String)
For Each oValue As String In oSheet.Range("B2:B8").Value2
oTest.Add(oValue)
Next
' Using an array
Dim oData(200) As Integer
Dim iCounter As Integer = 0
For Each oValue As String In oSheet.Range("B2:B8").Value2
oData(iCounter) = CType(oValue, Integer)
iCounter += 1
Next
oExcel.Quit()
I think your approach is good, accessing the file with OleDB and not openning an instance of Excel.
I used a DataReader and DataTable to collect and hold the data in memory.
The Using...End Using blocks ensure your objects that have a Dispose method are closed and disposed properly even if there is an error.
Private Sub LoadData()
Dim dt As New DataTable()
Dim conStr As String = "Your connection string"
Using con As New OleDbConnection(conStr)
Dim query As String = "SELECT * FROM [Sheet1$]"
Using cmd As New OleDbCommand(query, con)
con.Open()
Using dr As OleDbDataReader = cmd.ExecuteReader()
dt.Load(dr)
End Using
End Using
End Using
'The number of rows in the DataTable less the first 2 rows which are title and blank
'and subtract 1 because vb.net arrays are defined array(upper bound)
Dim arraySize As Integer = dt.Rows.Count - 3
Dim myData(arraySize) As Integer
Dim arrayIndex As Integer = 0
'Putting data indide array
For rowIndex As Integer = 2 To dt.Rows.Count - 1
myData(arrayIndex) = CInt(dt.Rows(rowIndex)(3)) '3 is the index of the TechID column
arrayIndex += 1
Next
'Checking the array - delete in final version
'I used i as a variable name because this is a very tiny
'loop and will be deleted eventually. Otherwise, I would
'have used a more descriptive name.
For Each i As Integer In myData
Debug.Print(i.ToString)
Next
End Sub
I have one combobox in my app that gets populated with a dozen or so items from SQL SERVER. I am currently trying to allow user to be able to type in a new value into the combobox and save it to a table in SQL SERVER. I'm looking for something along the lines of a DropDownStyle of DropDown and DropDownList. Basically I'm hoping to let the user type in the combobox, however if the value is not there, i want to be able to give them an option of saving it (probably on lost focus). I'm wondering what would be a good way of doing something like that.
On lost focus should I basically go through each item that is currently in the drop down and check it against the value entered?
EDIT:
Sql="SELECT IDvalue, TextName from TblReference"
Dim objconn As New SqlConnection
objconn = New SqlConnection(conn)
objconn.Open()
Dim da As New SqlDataAdapter(sql, objconn)
Dim ds As New DataSet
da.Fill(ds, "Name")
If ds.Tables("Name").Rows.Count > 0 Then
Dim dr As DataRow = ds.Tables("Name ").NewRow
ds.Tables("Name").Rows.InsertAt(dr, 0)
With c
.DataSource = ds.Tables("Name")
.ValueMember = " IDvalue "
.DisplayMember = " TextName "
End With
End If
You are already adding a fake/blank row to a table, you can do the same thing for a new item.
' form level datatable var
Private cboeDT As DataTable
Initializing:
cboeDT = New DataTable
Dim sql = "SELECT Id, Descr FROM TABLENAME ORDER BY Descr"
Using dbcon As New MySqlConnection(MySQLConnStr)
Using cmd As New MySqlCommand(sql, dbcon)
dbcon.Open()
cboeDT.Load(cmd.ExecuteReader())
' probably always need this even
' when there are no table rows (???)
Dim dr = cboeDT.NewRow
dr("Id") = -1 ' need a way to identify it
dr("Descr") = ""
cboeDT.Rows.InsertAt(dr, 0)
End Using
End Using
cboeDT.DefaultView.Sort = "Descr ASC"
cboE.DataSource = cboeDT
cboE.DisplayMember = "Descr"
cboE.ValueMember = "Id"
Note Users tend to have a preference as to the order of these things. The simple creatures tend to prefer alphabetical over a DB Id they may never see. To accommodate them, the DefaultView is sorted so that any new rows added will display in the correct order.
Add new items in the Leave event (much like Steve's):
Private Sub cboE_Leave(sender ...
' if it is new, there will be no value
If cboE.SelectedValue Is Nothing Then
' alternatively, search for the text:
'Dim item = cboeDT.AsEnumerable().
' FirstOrDefault(Function(q) String.Compare(q.Field(Of String)("Descr"),
' cboE.Text, True) = 0)
'If item Is Nothing Then
' ' its new...
Dim newid = AddNewItem(cboE.Text)
Dim dr = cboeDT.NewRow
dr("Id") = newid
dr("Descr") = cboE.Text
cboeDT.Rows.Add(dr)
' fiddling with the DS looses the selection,
' put it back
cboE.SelectedValue = newid
End If
End Sub
If you want to search by text:
Dim item = cboeDT.AsEnumerable().
FirstOrDefault(Function(q) String.Compare(q.Field(Of String)("Descr"),
cboE.Text, True) = 0)
If item Is Nothing Then
' its new...
...
Inserting will vary a little depending on the actual db. A key step though is to capture and return the ID of the new item since it is needed for the CBO:
Private Function AddNewItem(newItem As String) As Int32
Dim sql = "INSERT INTO MY_TABLE (Descr) VALUES (#v); SELECT LAST_INSERT_ID();"
Dim newId = -1
Using dbcon As New MySqlConnection(MySQLConnStr)
Using cmd As New MySqlCommand(sql, dbcon)
dbcon.Open()
cmd.Parameters.Add("#v", MySqlDbType.String).Value = newItem
' MySql provides it in the command object
If cmd.ExecuteNonQuery() = 1 Then
newId = Convert.ToInt32(cmd.LastInsertedId)
End If
End Using
End Using
Return newId
End Function
As noted MySql provides the LastInsertedID as a command object property. In SQL SERVER, tack ...";SELECT LAST_INSERT_ID();" to the end of your SQL and then:
newId = Convert.ToInt32(cmd.ExecuteScalar())
This is not conceptually very different from Steve's answer, except it uses the DataTable you build rather than collections which makes it (very) slightly simpler.
The way I do this, is on window load I perform a new SQL query to get the list of values in the table, and load them into a combobox.
Then once focus is lost, it then checks what's currently typed into the combobox against the current values already loaded. If it doesn't exist, then it's not in SQL. Something like the following...
Dim found As Boolean = False
For i As Integer = 0 To comboBox.Items.Count - 1
Dim value As String = comboBox.Items(i).ToString()
If comboBox.Text = value Then
found = True
End If
Next
If found = False Then
'the item doesn't exist.. add it to SQL
Else
'the item exists.. no need to touch SQL
End If
First thing I would do is to build a simple class to hold your values through a List of this class
Public Class DataItem
Public Property IDValue As Integer
Public Property TextName as String
End Class
Now, instead of building an SqlDataAdapter and fill a dataset, work with an SqlDataReader and build a List(Of DataItem)
' Class global...
Dim allItems = new List(Of DataItem)()
Sql="SELECT IDvalue, TextName from TblReference"
' Using to avoid leaks on disposable objects
Using objconn As New SqlConnection(conn)
Using cmd As New SqlCommand(Sql, objconn)
objconn.Open()
Using reader = cmd.ExecuteReader()
While reader.Read()
Dim item = new DataItem() With { .IDValue = reader.GetInt32(0), .TextName = reader.GetString(1)}
allItems.Add(item)
End While
End Using
if allItems.Count > 0 Then
allItems.Insert(0, new DataItem() With {.IDValue = -1, .TextValue = ""}
Dim bs = new BindingList(Of DataItem)(allItems)
c.DataSource = bs
c.ValueMember = "IDvalue"
c.DisplayMember = "TextName"
End If
End Using
End Using
Now the code that you want to add to your Leave event for the combobox
Sub c_Leave(sender As Object, e As EventArgs) Handles c.Leave
If Not String.IsNullOrEmpty(c.Text) Then
Dim bs = DirectCast(c.DataSource, BindingList(Of DataItem))
if bs.FirstOrDefault(Function(x) x.TextName = c.Text) Is Nothing Then
Dim item = new DataItem() With { .IDValue = -1, .TextName = c.Text}
bs.Add(item)
' here add the code to insert in the database
End If
End If
End Sub
I've written a function which reads csv files and parametrizes them accordingly, therefore i have a function gettypessql which queries sql table at first to get data types and therefore to adjust the columns which are later inserted in sql. So my problem is when I set HDR=Yes in Jet OLE DB I get only column names like F1, F2, F3. To circumvent this issue I've set HDR=No and written some for loops but now I get only empty strings, what is actually the problem? here is my code:
Private Function GetCSVFile(ByVal file As String, ByVal min As Integer, ByVal max As Integer) As DataTable
Dim ConStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & TextBox1.Text & ";Extended Properties=""TEXT;HDR=NO;IMEX=1;FMT=Delimited;CharacterSet=65001"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim dt As New DataTable
Dim da As OleDb.OleDbDataAdapter = Nothing
getData = Nothing
Try
Dim CMD As String = "Select * from " & _table & ".csv"
da = New OleDb.OleDbDataAdapter(CMD, conn)
da.Fill(min, max, dt)
getData = New DataTable(_table)
Dim firstRow As DataRow = dt.Rows(0)
For i As Integer = 0 To dt.Columns.Count - 1
Dim columnName As String = firstRow(i).ToString()
Dim newColumn As New DataColumn(columnName, mListOfTypes(i))
getData.Columns.Add(newColumn)
Next
For i As Integer = 1 To dt.Rows.Count - 1
Dim row As DataRow = dt.Rows(i)
Dim newRow As DataRow = getData.NewRow()
For j As Integer = 0 To getData.Columns.Count - 1
If row(j).GetType Is GetType(String) Then
Dim colValue As String = row(j).ToString()
colValue = ChangeEncoding(colValue)
colValue = ParseString(colValue)
colValue = ReplaceChars(colValue)
newRow(j) = colValue
Else
newRow(j) = row(j)
End If
Next
getData.Rows.Add(newRow)
Application.DoEvents()
Next
Catch ex As OleDbException
MessageBox.Show(ex.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
dt.Dispose()
da.Dispose()
End Try
Return getData
End Function
and get types sql, this one doesn't convert properly, especially doubles
Private Sub GetTypesSQL()
If (mListOfTypes Is Nothing) Then
mListOfTypes = New List(Of Type)()
End If
mListOfTypes.Clear()
Dim dtTabelShema As DataTable = db.GetDataTable("SELECT TOP 0 * FROM " & _table)
Using dtTabelShema
For Each col As DataColumn In dtTabelShema.Columns
mListOfTypes.Add(col.DataType)
Next
End Using
End Sub
I think you have made it more complicated than it needs to be. For instance, you get the dbSchema by creating an empty DataTable and harvesting the Datatypes from it. Why not just use that first table rather than creating a new table from the Types? The table also need not be reconstructed over and over for each batch of rows imported.
Generally since OleDb will try to infer types from the data, it seems unnecessary and may even get in the way in some cases. Also, you are redoing everything that OleDB does and copying data to a different DT. Given that, I'd skip the overhead OleDB imposes and work with the raw data.
This creates the destination table using the CSV column name and the Type from the Database. If the CSV is not in the same column order as those delivered in a SELECT * query, it will fail.
The following uses a class to map csv columns to db table columns so the code is not depending on the CSVs being in the same order (since they may be generated externally). My sample data CSV is not in the same order:
Public Class CSVMapItem
Public Property CSVIndex As Int32
Public Property ColName As String = ""
'optional
Public Property DataType As Type
Public Sub New(ndx As Int32, csvName As String,
dtCols As DataColumnCollection)
CSVIndex = ndx
For Each dc As DataColumn In dtCols
If String.Compare(dc.ColumnName, csvName, True) = 0 Then
ColName = dc.ColumnName
DataType = dc.DataType
Exit For
End If
Next
If String.IsNullOrEmpty(ColName) Then
Throw New ArgumentException("Cannot find column: " & csvName)
End If
End Sub
End Class
The code to parse the csv uses CSVHelper but in this case the TextFieldParser could be used since the code just reads the CSV rows into a string array.
Dim SQL = String.Format("SELECT * FROM {0} WHERE ID<0", DBTblName)
Dim rowCount As Int32 = 0
Dim totalRows As Int32 = 0
Dim sw As New Stopwatch
sw.Start()
Using dbcon As New MySqlConnection(MySQLConnStr)
Using cmd As New MySqlCommand(SQL, dbcon)
dtSample = New DataTable
dbcon.Open()
' load empty DT, create the insert command
daSample = New MySqlDataAdapter(cmd)
Dim cb = New MySqlCommandBuilder(daSample)
daSample.InsertCommand = cb.GetInsertCommand
dtSample.Load(cmd.ExecuteReader())
' dtSample is not only empty, but has the columns
' we need
Dim csvMap As New List(Of CSVMapItem)
Using sr As New StreamReader(csvfile, False),
parser = New CsvParser(sr)
' col names from CSV
Dim csvNames = parser.Read()
' create a map of CSV index to DT Columnname SEE NOTE
For n As Int32 = 0 To csvNames.Length - 1
csvMap.Add(New CSVMapItem(n, csvNames(n), dtSample.Columns))
Next
' line data read as string
Dim data As String()
data = parser.Read()
Dim dr As DataRow
Do Until data Is Nothing OrElse data.Length = 0
dr = dtSample.NewRow()
For Each item In csvMap
' optional/as needed type conversion
If item.DataType = GetType(Boolean) Then
' "1" wont convert to bool, but (int)1 will
dr(item.ColName) = Convert.ToInt32(data(item.CSVIndex).Trim)
Else
dr(item.ColName) = data(item.CSVIndex).Trim
End If
Next
dtSample.Rows.Add(dr)
rowCount += 1
data = parser.Read()
If rowCount = 50000 OrElse (data Is Nothing OrElse data.Length = 0) Then
totalRows += daSample.Update(dtSample)
' empty the table if there will be more than 100k rows
dtSample.Rows.Clear()
rowCount = 0
End If
Loop
End Using
End Using
End Using
sw.Stop()
Console.WriteLine("Parsed and imported {0} rows in {1}", totalRows,
sw.Elapsed.TotalMinutes)
The processing loop updates the DB every 50K rows in case there are many many rows. It also does it in one pass rather than reading N rows thru OleDB at a time. CsvParser will read one row at a time, so there should never be more than 50,001 rows worth of data on hand at a time.
There may be special cases to handle for type conversions as shown with If item.DataType = GetType(Boolean) Then. A Boolean column read in as "1" cant be directly passed to a Boolean column, so it is converted to integer which can. There could be other conversions such as for funky dates.
Time to process 250,001 rows: 3.7 mins. An app which needs to apply those string transforms to every single string column will take much longer. I'm pretty sure that using the CsvReader in CSVHelper you could have those applied as part of parsing to a Type.
There is a potential disaster waiting to happen since this is meant to be an all-purpose importer/scrubber.
For i As Integer = 0 To dt.Columns.Count - 1
Dim columnName As String = firstRow(i).ToString()
Dim newColumn As New DataColumn(columnName, mListOfTypes(i))
getData.Columns.Add(newColumn)
Next
Both the question and the self-answer build the new table using the column names from the CSV and the DataTypes from a SELECT * query on the destination table. So, it assumes the CSV Columns are in the same order that SELECT * will return them, and that all CSVs will always use the same names as the tables.
The answer above is marginally better in that it finds and matches based on name.
A more robust solution is to write a little utility app where a user maps a DB column name to a CSV index. Save the results to a List(Of CSVMapItem) and serialize it. There could be a whole collection of these saved to disk. Then, rather than creating a map based on dead reckoning, just deserialize the desired for user as the csvMap in the above code.
I am trying to read fields from a query into a text string arrary. In vb6 I can simply declare the array and then read the fields into it without it caring what type of values are in it. Now when I try to do that same thing I get an "unable to cast com object of type 'dao.fieldclass' to type 'system.string". Do I need to read the field value into a seperarte variable and then convert it to a string? The seqNum is what I am having the problem with
Public dbEngine As dao.DBEngine
Public db As dao.Database, recSet As dao.Recordset
dbEngine = New dao.DBEngine
Dim seqNum As Long
scExportTemplatePath = "M:\robot\scTemplates\"
db = dbEngine.OpenDatabase(scExportStuffPath & "scExport.mdb")
tsOut = fso.CreateTextFile(wildePath & dte & "-" & fle.Name & ".csv", True)
With recSet
.MoveFirst()
Do While Not .EOF
seg = .Fields("segmentID")
If seg <> segHold Then
seqNum = 1
End If
arrOut(0) = .Fields("jobnum_AM")
Loop
End With
You have several problems with this code. In addition to the points mentioned by Jeremy:
What was Long in VB6 is now Integer in VB.NET. Long is a 64 bit integer now.
Use System.IO.Path.Combine in order to combine path strings. Combine automatically adds missing backslashes and removes superfluous ones. Path.Combine(scExportTemplatePath, "scExport.mdb")
The Field property does not have a default property any more. Non-indexed properties are never default properties in VB.NET. Get the field value with .Fields("segmentID").Value.
Convert its value to the appropriate type: seg = Convert.ToInt32(.Fields("segmentID").Value)
Note: VB's Integer type is just an alias for System.Int32.
You are always adding to the same array field. I don't know exactly what you have in mind. If you want to add one field only, you could just use a List(Of String). If you are adding several fields for each record, then a List(Of String()) (i.e. a list of string arrays) would be appropriate. Lists have the advantage that they grow automatically.
Dim list As New List(Of String())
Do While Not .EOF
Dim values = New String(2) {}
values(0) = Convert.ToString(.Fields("field_A").Value)
values(1) = Convert.ToString(.Fields("field_B").Value)
values(2) = Convert.ToString(.Fields("field_C").Value)
list.Add(values)
recSet.MoveNext()
Loop
But it is more comprehensible, if you create a custom class for storing your field values:
Console.WriteLine("{0} {1} ({2})", user.FirstName, user.LastName, user.DateOfBirth)
... reads much better than:
Console.WriteLine("{0} {1} ({2})", values(0), values(1), values(2))
In VB.NET you have other possibilities to work with databases:
Dim list As New List(Of String())
Using conn = New OleDb.OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyPath\MyDb.mdb")
Dim sql = "SELECT myStuff FROM myTable"
Dim command = New OleDbCommand(sql, conn)
conn.Open()
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
Dim values = New String(reader.FieldCount - 1) {}
For i = 0 To reader.FieldCount - 1
values(i) = Convert.ToString(reader.GetValue(i))
Next
list.Add(values)
End While
End Using
End Using
Note that the Using statement closes the resources automatically at the end. Even if an error occurs and the code is terminated prematurely.
In VB.NET you can write to files like this (without using fso, which is not .NET like)
Using writer As New StreamWriter("myFile.txt", False)
writer.WriteLine("line 1")
writer.WriteLine("line 2")
writer.WriteLine("line 3")
End Using
1) You dont show how you open the Recordset, eg:
Set recSet = db.OpenRecordset("query_name or SQL")
2) You dont have a .MoveNext in the While Loop:
With recSet
.MoveFirst()
Do While Not .EOF
seg = .Fields("segmentID")
If seg <> segHold Then
seqNum = 1
End If
arrOut(0) = .Fields("jobnum_AM")
.MoveNext()
loop
I have a function that returns a list of account numbers as an Arraylist. I am trying to use each account as a command parameter in another sub routine to get more data about each account number. This only returns the data for the last account number in the arraylist. I need to use each account number, call the database, get the additional information and store ALL of the data into a Gridview (databind). Example: If I had 3 account numbers in my arraylist return 3 rows of data to the gridview. I am struggling with how to get ALL of the information for each value (account number) in the Arraylist. Can someone point me in the right direction?? I think this can be done but I am not certain if my approach is correct or not. Perhaps I need to create datatables that contain the additional information for each value passed via the arraylist....Any Ideas??
#jwatts1980 thanks for the comment: I will try to clarify. I have an arraylist of account numbers (and maybe this is where I am off track) I am trying to use the values in this ArrayList as command parameters in another call to a different table/file that returns more info on those accounts. I will provide a portion of the code to help clarify what it is I am attempting to do:
Private Function ReturnMultAccts(ByVal strAcct) As ArrayList
Dim acctsDetail As New ArrayList
Dim dsn As String = ConfigurationManager.ConnectionStrings.ConnectionString
Dim sql As String = "SELECT DISTINCT * FROM FILE WHERE ACCTNUM=?"
Using conn As New OdbcConnection(dsn)
Using cmd As New OdbcCommand(sql, conn)
conn.Open()
cmd.Parameters.Add("ACCTNUM", OdbcType.VarChar, 20).Value = strAcct
Dim rdrUsers As OdbcDataReader = cmd.ExecuteReader()
If rdrUsers.HasRows Then
While rdrUsers.Read()
acctsDetail.Add(Trim(rdrUsers.Item("ACCTNUM")))
End While
End If
rdrUsers.Close()
conn.Close()
End Using
End Using
This returns an Arraylist of Account Numbers (Lets say it is 3 acct numbers). I call this Function from another Sub:
Private Sub GetMoreAcctInfo(ByVal strAcct)
'Create New ArrayList
Dim MultAccts As New ArrayList
'Pass strAcct to Function to get Multiples
MultAccts = ReturnMultAccts(strAcct)
'Create the variable BachNum for the loop
Dim BachNum As String = MultAccts.Item(0)
For Each BachNum In MultAccts
'Get All of the necessary info from OtherFile based on the BachNum for BOS's
Dim dsn As String = ConfigurationManager.ConnectionStrings.ConnectionString
Dim sql As String = "SELECT ACCTNUM, BILSALCOD1, BILSALCOD2, BILSALCOD3, OTHACCTNUM FROM OtherFile WHERE OTHACCTNUM=?" 'Equal to the items in the arraylist
Using conn As New OdbcConnection(dsn)
Using cmd As New OdbcCommand(sql, conn)
conn.Open()
cmd.Parameters.Add("OTHACCTNUM", OdbcType.VarChar, 20).Value = BachNum
Using adapter = New OdbcDataAdapter(cmd)
Dim DS As New DataSet()
adapter.Fill(DS)
GridView1.DataSource = DS
GridView1.DataBind()
End Using
End Using
End Using
Next
End Sub
Hopefully this clarifies what I am attempting to do...??
To elaborate on my suggestion, you will need a list of strongly typed objects. You can add those items to the list, then bind the list to the GridView.
I'll start at the beginning. You know what kind of data is coming from your database: ACCTNUM, BILSALCOD1, BILSALCOD2, BILSALCOD3, and OTHACCTNUM. So you can use those to create an object.
Friend Class AccountClass
Private pACCTNUM As string = ""
Private pBILSALCOD1 As string = ""
Private pBILSALCOD2 As string = ""
Private pBILSALCOD3 As string = ""
Private pOTHACCTNUM As string = ""
Public Property ACCTNUM() As string
Get
Return pACCTNUM
End Get
Set(ByVal value as string)
Me.pACCTNUM = value
End Set
End Property
Public Property BILSALCOD1() As string
Get
Return pBILSALCOD1
End Get
Set(ByVal value as string)
Me.pBILSALCOD1 = value
End Set
End Property
Public Property BILSALCOD2() As string
Get
Return pBILSALCOD2
End Get
Set(ByVal value as string)
Me.pBILSALCOD2 = value
End Set
End Property
Public Property BILSALCOD3() As string
Get
Return pBILSALCOD3
End Get
Set(ByVal value as string)
Me.pBILSALCOD3 = value
End Set
End Property
Public Property OTHACCTNUM() As string
Get
Return pOTHACCTNUM
End Get
Set(ByVal value as string)
Me.pOTHACCTNUM = value
End Set
End Property
Sub New(ByVal ACCTNUM As string, ByVal BILSALCOD1 As string, ByVal BILSALCOD2 As string, ByVal BILSALCOD3 As string, ByVal OTHACCTNUM As string)
Me.ACCTNUM = ACCTNUM
Me.BILSALCOD1 = BILSALCOD1
Me.BILSALCOD2 = BILSALCOD2
Me.BILSALCOD3 = BILSALCOD3
Me.OTHACCTNUM = OTHACCTNUM
End Sub
End Class
Then you rework the GetMoreAcctInfo() routine to use it.
Private Sub GetMoreAcctInfo(ByVal strAcct)
'Create New ArrayList
Dim MultAccts As ArrayList
'Pass strAcct to Function to get Multiples
MultAccts = ReturnMultAccts(strAcct)
'Create the variable BachNum for the loop
Dim BachNum As String
'Create the list to bind to the grid
Dim AcctInfo As New Generic.List(Of AccountClass)
'create the dataset
Dim DS As DataSet
For Each BachNum In MultAccts
'Get All of the necessary info from OtherFile based on the BachNum for BOS's
Dim dsn As String = ConfigurationManager.ConnectionStrings.ConnectionString
Dim sql As String = "SELECT ACCTNUM, BILSALCOD1, BILSALCOD2, BILSALCOD3, OTHACCTNUM FROM OtherFile WHERE OTHACCTNUM=?" 'Equal to the items in the arraylist
Using conn As New OdbcConnection(dsn)
Using cmd As New OdbcCommand(sql, conn)
conn.Open()
cmd.Parameters.Add("OTHACCTNUM", OdbcType.VarChar, 20).Value = BachNum
Using adapter = New OdbcDataAdapter(cmd)
DS = New DataSet()
adapter.Fill(DS)
For Each t As DataTable In DS.Tables
For Each r As DataRow In t.Rows
AcctInfo.Add(new AccountClass(r("ACCTNUM"), r("BILSALCOD1"), r("BILSALCOD2"), r("BILSALCOD3"), r("OTHACCTNUM")))
Next
Next
End Using
End Using
End Using
Next
GridView1.DataSource = AcctInfo
GridView1.DataBind()
End Sub