How can I return an array of string from a function? - arrays

I'm trying to get three string values from a query, but this call to the function:
argVals = GetArgValsForCompanyName(coName)
...fails to compile with the err msg, "Value of type 'String' cannot be converted to '1-dimensional array of String'."
Nor does this line at the end of that function compile:
Return args
...which fails with, "Value of type '1-dimensional array of String' cannot be converted to 'String'."
I am declaring argVals like so, as an array of string of three vals:
Dim argVals(2) As String
...and the function like so:
Protected Function GetArgValsForCompanyName(coName As String) As String
For more context, here is the pertinent code in its (I think) entirety:
Private Sub Button1_Click( sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr As String = "SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=vonnegut;PWD=ryecatcher"
Dim upd8DML As String = "UPDATE CustomerCategoryLog SET Category = 'Exploding' WHERE Unit = #Unit And MemberNo = #MemberNo AND Custno = #CustNo"
Dim coName As String
Dim argVals(2) As String
Dim _Unit As String
Dim _MemberNo As String
Dim _CustNo As String
Dim curIndexVal As String
For Each cntrl As Control In Me.Controls
If TypeOf cntrl Is CheckBox Then
If DirectCast(cntrl, CheckBox).Checked = True Then
curIndexVal = CStr(DirectCast(cntrl, CheckBox).Tag)
coName = GetLabelTextForID(curIndexVal)
argVals = GetArgValsForCompanyName(coName)
_Unit = argVals(0)
_MemberNo = argVals(1)
_CustNo = argVals(2)
Using conn As New SqlConnection(connStr), _
cmd As New SqlCommand(upd8DML, conn)
cmd.Parameters.Add("#Unit", SqlDbType.VarChar, 50).Value = _Unit
cmd.Parameters.Add("#MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
cmd.Parameters.Add("#CustNo", SqlDbType.VarChar, 50).Value = _CustNo
conn.Open
cmd.ExecuteScalar()
End Using
End If
End If
Next
End Sub
Protected Function GetArgValsForCompanyName(coName As String) As String
Dim args(2) As String
Dim sqlConnection1 As New SqlConnection("SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=salinger;PWD=dresdenoflions")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "select Unit, MemberNo, CustNo from Customers WHERE CompanyName = #CoName"
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#CoName", SqlDbType.VarChar, 50).Value = coName
cmd.Connection = sqlConnection1
sqlConnection1.Open()
sqlConnection1.Open()
reader = cmd.ExecuteReader()
If reader.HasRows Then
args(0) = reader.Item(0).ToString()
args(1) = reader.Item(1).ToString()
args(2) = reader.Item(2).ToString()
End If
reader.Close()
sqlConnection1.Close()
Return args
End Function
What am I getting wrong here? How can I pass back an array of string from a function, and then store those vals in three vars (dims)?
NOTE: If I try to declare the function like so:
Protected Function GetArgValsForCompanyName(coName As String) As String(2)
...I get, "Array bounds cannot appear in type specifiers"

Your problem seems to be that you have the function signiture like so
Protected Function GetArgValsForCompanyName(coName As String) As String
When it should be like this
Protected Function GetArgValsForCompanyName(coName As String) As String()
The () at the end of the return type states that it will be a string array, and not just a string.

Related

MultipleActiveResultSets for SQL Server and VB.NET application

I am trying to get multiple data sets from SQL Server using a VB.NET application. The problem that every time I try to execute the query,
I get this message:
Cannot change property 'ConnectionString'. The current state of the connection is open
Then I tried to fix it by enabling MARS
<connectionStrings>
<add name="ConString"
providerName="System.Data.SqlClient"
connectionString="Data Source=my-PC;Initial Catalog=Project;Persist Security Info=True; MultipleActiveResultSets=true;User ID=user;Password=*****" />
</connectionStrings>
This is my code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim obj, body
obj = TextBox1.Text
body = TextBox2.Text
For Each mail In getemail()
Send_mail(mail, obj, body, getattachment(mail))
Next
MsgBox("Traitement effectué")
End Sub
Function getemail() As List(Of String)
Dim strMailTo As New List(Of String)
Dim SQL As String = "Select EMail FROM [USER] WHERE EMail Is Not NULL And MatriculeSalarie Is Not NULL And [EMail] <> '' and EtatPaie = 3 and BulletinDematerialise = 1 "
Dim cmd As New SqlCommand
Dim sqLdr As SqlDataReader
Dim dr As DataRow
Try
ConnServer()
cmd.Connection = con
cmd.CommandText = SQL
Using sda As New SqlDataAdapter(cmd)
Using ds As New DataTable()
sda.Fill(ds)
sqLdr = cmd.ExecuteReader()
For i = 0 To ds.Rows.Count - 1
dr = ds.Rows(i)
strMailTo.Add(dr("EMail"))
Next
End Using
End Using
Return strMailTo
sqLdr.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
closeCon()
Return strMailTo
End Function
Function getattachment(email) As String()
Dim SQL As String = "Select MatriculeSalarie FROM [USER] WHERE [EMail]='" & email & "'"
Dim cmd As New SqlCommand
Dim sqLdr As SqlDataReader
ConnServer()
cmd.Connection = con
cmd.CommandText = SQL
Dim mat As String
mat = ""
Dim Dir As String = ConfigurationManager.AppSettings("path1").ToString
Dim file()
sqLdr = cmd.ExecuteReader()
While sqLdr.Read
mat = sqLdr.GetValue(sqLdr.GetOrdinal("MatriculeSalarie"))
End While
file = IO.Directory.GetFiles(Dir, mat.Substring(1) & "*.pdf")
sqLdr.Close()
Return file
End Function
If all you are going to do is show a message box in a Catch, don't do it in the database code. Let the error bubble up to the user interface code and put the Try around where the method is called.
Do not declare variables without a DataType. The button code with Option Infer on sets the type of obj and body.
Private ConStr As String = "Your connection string"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim obj = TextBox1.Text
Dim body = TextBox2.Text
Dim emails As New List(Of String)
Try
emails = getemail()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Error retrieving email list")
Exit Sub
End Try
For Each email In emails
Try
Send_mail(email, obj, body, getattachment(email))
Catch ex As Exception
MessageBox.Show(ex.Message, "Error getting attachments")
End Try
Next
MessageBox.Show("Traitement effectué")
End Sub
Parameters used by Sub and Function must have a DataType.
I don't know what you are doing here.
While sqLdr.Read
mat = sqLdr.GetValue(sqLdr.GetOrdinal("MatriculeSalarie"))
End While
Each iteration will overwrite the previous value of mat. I can only assume that you expect only a single value, in which case you can use ExecuteScalar to get the first column of the first row of the result set. Don't do anything with the data until after the connection is closed. Just get the raw data and close (End Using) the connection. Manipulate the data later.
Always use Parameters. Parameters are not treated as executable code by the database server. They are simply values. An example of executable code that could be inserted is "Drop table [USER];" where the value of a parameter belongs. Oops!
Function getemail() As List(Of String)
Dim SQL As String = "Select EMail FROM [USER]
WHERE EMail Is Not NULL
And MatriculeSalarie Is Not NULL
And [EMail] <> ''
And EtatPaie = 3
And BulletinDematerialise = 1;"
Dim dt As New DataTable
Using con As New SqlConnection("Your connection string"),
cmd As New SqlCommand(SQL, con)
con.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Dim strMailTo As New List(Of String)
strMailTo = (From row As DataRow In dt.AsEnumerable
Select row.Field(Of String)(0)).ToList
Return strMailTo
End Function
Function getattachment(email As String) As String()
Dim SQL As String = "Select MatriculeSalarie FROM [USER] WHERE [EMail]='" & email & "'"
Dim mat As String
Using con As New SqlConnection(ConStr),
cmd As New SqlCommand(SQL, con)
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = email
con.Open()
mat = cmd.ExecuteScalar().ToString()
End Using
Dim Dir As String = ConfigurationManager.AppSettings("path1").ToString
'Your original code was fine, no need for searchPattern.
'I added this so you could see if your search pattern was what you expected.
Dim searchPattern = mat.Substring(1) & "*.pdf"
Debug.Print(searchPattern) 'Appears in the Immediate window
Dim file = IO.Directory.GetFiles(Dir, searchPattern)
Return file
End Function

Null value of DataReader in List(of string) vb.net

I am writing a web service function in VB.net in a stored procedure in SQL server. I think the DataReader does not return any value.
Here is my stored procedure in Sql Server:
Create proc getVillageName
#village varchar(50)
as
Begin
SELECT
lookup_table.value FROM dbo.lookup_table INNER JOIN dbo.lookup_description ON
lookup_table.group_id = lookup_description.desc_id WHERE
lookup_description.description = 'Village' AND
lookup_table.value LIKE #village + '%'
End
Here is my code:
Public Function GetVillage(ByVal villageName As String) As List(Of String)
Dim strsql As String
Dim Villagevalue As List(Of String)
Dim param As SqlParameter
Dim conn As New SqlConnection With {.ConnectionString = "Server=MINTOY_DEV\MIGSSERVER;Database=SouthLinkDBO;User=sa;Pwd=123;"}
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
Using conn
strsql = "getVillageName"
cmd = New SqlCommand(strsql, conn)
cmd.CommandType = CommandType.StoredProcedure
param = New SqlParameter("#village", villageName)
cmd.Parameters.Add(param)
conn.Open()
reader = cmd.ExecuteReader
While reader.Read
Villagevalue.Add(reader.Item("value").ToString)
End While
End Using
End Function
You're missing a line:
While reader.Read
Villagevalue.Add(reader.Item("value").ToString)
End While
End Using
Return Villagevalue '<-----------------
End Function
Are you looking at compiler warnings? VB will tell you if you forget a Return statement.
Better yet, open the Project Properties, click on the Compiler tab, and set "Function returning a reference type without a return value" to "Error".
Also, how is this working at all?
Dim Villagevalue As List(Of String)
That should be
Dim Villagevalue As New List(Of String)
Lots of things we can improve here:
Public Iterator Function GetVillage(ByVal villageName As String) As IEnumerable(Of String)
Using conn As New SqlConnection("Server=MINTOY_DEV\MIGSSERVER;Database=SouthLinkDBO;User=sa;Pwd=123;"), _
cmd As New SqlCommand("getVillageName", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#village", SqlDbType.VarChar, 50).Value = villageName
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Yield DirectCast(reader("value"), String)
End While
End Using
End Using
End Function
The big thing is we actually return a value (Yield handles this for Iterator functions).
If you really need an actual List(Of String) (Hint: you usually don't; Your code will almost always perform a lot better if you arrange things to work with IEnumerable(Of T) for as long as possible) you can append a .ToList() when calling this method.

How to import text file in vb.net and insert into SQL server?

I'm trying to import a text file into an SQL server. I need to read data inside the file when I upload it and send all the data to an SQL server. Of course inside the SQL I have primary keys where it's going to increment when a new line of data is finished.
HELP!
With Cinchoo ETL - an open source ETL framework, you can load the entire file to database with few lines of code as below (the code is in c#, hope you can translate it to vb.net)
string connectionstring =
#"Data Source=(localdb)\v11.0;Initial Catalog=TestDb;Integrated Security=True";
using (SqlBulkCopy bcp = new SqlBulkCopy(connectionstring))
{
using (var dr = new ChoCSVReader<Customer>
("Cust.csv").WithFirstLineHeader().AsDataReader())
{
bcp.DestinationTableName = "dbo.Customers";
bcp.EnableStreaming = true;
bcp.BatchSize = 10000;
bcp.BulkCopyTimeout = 0;
bcp.NotifyAfter = 10;
bcp.SqlRowsCopied += delegate (object sender, SqlRowsCopiedEventArgs e)
{
Console.WriteLine(e.RowsCopied.ToString("#,##0") + " rows copied.");
};
bcp.WriteToServer(dr);
}
}
For more details, visit the codeproject article
Disclosure: I'm the author of this library.
This is an interesting question. I did this a looonnngggg time ago. See the code below, for a solution to your question.
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
Also, see ALL the code below, for several similar, and related, tasks. Notice, I added a few comments, but not too many...
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb
Imports System.Configuration
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Dim str As String = ""
Using sw As New IO.StreamWriter("C:\Users\Excel\Desktop\OrdersTest.csv")
sw.WriteLine(String.Join(",", headers))
'sw.WriteLine(String.Join(","))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
sw.Close()
End Using
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'Dim m_strConnection As String = "server=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;"
'Catch ex As Exception
' MessageBox.Show(ex.ToString())
'End Try
'Dim objDataset1 As DataSet()
'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim da As OdbcDataAdapter
Dim OpenFile As New System.Windows.Forms.OpenFileDialog ' Does something w/ the OpenFileDialog
Dim strFullPath As String, strFileName As String
Dim tbFile As New TextBox
' Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*" ' Shows only .csv files
OpenFile.Title = "Browse to file:" ' Title at the top of the dialog box
If OpenFile.ShowDialog() = DialogResult.OK Then ' Makes the open file dialog box show up
strFullPath = OpenFile.FileName ' Assigns variable
strFileName = Path.GetFileName(strFullPath)
If OpenFile.FileNames.Length > 0 Then ' Checks to see if they've picked a file
tbFile.Text = strFullPath ' Puts the filename in the textbox
' The connection string for reading into data connection form
Dim connStr As String
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt "
' Sets up the data set and gets stuff from .csv file
Dim Conn As New OdbcConnection(connStr)
Dim ds As DataSet
Dim DataAdapter As New OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn)
ds = New DataSet
Try
DataAdapter.Fill(ds, strFileName) ' Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName) ' ..according to data source
' Catch and display database errors
Catch ex As OdbcException
Dim odbcError As OdbcError
For Each odbcError In ex.Errors
MessageBox.Show(ex.Message)
Next
End Try
' Cleanup
OpenFile.Dispose()
Conn.Dispose()
DataAdapter.Dispose()
ds.Dispose()
End If
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim cnn As SqlConnection
Dim connectionString As String
Dim sql As String
connectionString = "data source=Excel-PC\SQLEXPRESS;" & _
"initial catalog=NORTHWIND;Trusted_Connection=True"
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = "SELECT * FROM [Order Details]"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet
dscmd.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
cnn.Close()
End Sub
Private Sub ProductsDataGridView_CellFormatting(ByVal sender As Object,
ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
Handles DataGridView1.CellFormatting
If e.ColumnIndex = DataGridView1.Columns(3).Index _
AndAlso e.Value IsNot Nothing Then
'
If CInt(e.Value) < 10 Then
e.CellStyle.BackColor = Color.OrangeRed
e.CellStyle.ForeColor = Color.LightGoldenrodYellow
End If
'
End If
'
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Dim SQLConnectionString As String = "Data Source=Excel-PC\SQLEXPRESS;" & _
"Initial Catalog=Northwind;" & _
"Trusted_Connection=True"
' Open a connection to the AdventureWorks database.
Using SourceConnection As SqlConnection = _
New SqlConnection(SQLConnectionString)
SourceConnection.Open()
' Perform an initial count on the destination table.
Dim CommandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.Orders;", _
SourceConnection)
Dim CountStart As Long = _
System.Convert.ToInt32(CommandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", CountStart)
' Get data from the source table as a AccessDataReader.
'Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
' "Data Source=" & "C:\Users\Excel\Desktop\OrdersTest.txt" & ";" & _
' "Extended Properties=" & "text;HDR=Yes;FMT=Delimited"","";"
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & "C:\Users\Excel\Desktop\" & ";" & _
"Extended Properties=""Text;HDR=No"""
Dim TextConnection As New System.Data.OleDb.OleDbConnection(ConnectionString)
Dim TextCommand As New OleDbCommand("SELECT * FROM OrdersTest#csv", TextConnection)
TextConnection.Open()
Dim TextDataReader As OleDbDataReader = TextCommand.ExecuteReader(CommandBehavior.SequentialAccess)
' Open the destination connection.
Using DestinationConnection As SqlConnection = _
New SqlConnection(SQLConnectionString)
DestinationConnection.Open()
' Set up the bulk copy object.
' The column positions in the source data reader
' match the column positions in the destination table,
' so there is no need to map columns.
Using BulkCopy As SqlBulkCopy = _
New SqlBulkCopy(DestinationConnection)
BulkCopy.DestinationTableName = _
"dbo.Orders"
Try
' Write from the source to the destination.
BulkCopy.WriteToServer(TextDataReader)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
' Close the AccessDataReader. The SqlBulkCopy
' object is automatically closed at the end
' of the Using block.
TextDataReader.Close()
End Try
End Using
' Perform a final count on the destination table
' to see how many rows were added.
Dim CountEnd As Long = _
System.Convert.ToInt32(CommandRowCount.ExecuteScalar())
'Console.WriteLine("Ending row count = {0}", CountEnd)
'Console.WriteLine("{0} rows were added.", CountEnd - CountStart)
End Using
End Using
'Dim FILE_NAME As String = "C:\Users\Excel\Desktop\OrdersTest.csv"
'Dim TextLine As String
'If System.IO.File.Exists(FILE_NAME) = True Then
' Dim objReader As New System.IO.StreamReader(FILE_NAME)
' Do While objReader.Peek() <> -1
' TextLine = TextLine & objReader.ReadLine() & vbNewLine
' Loop
'Else
' MsgBox("File Does Not Exist")
'End If
'Dim cn As New SqlConnection("Data Source=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;")
'Dim cmd As New SqlCommand
'cmd.Connection = cn
'cmd.Connection.Close()
'cmd.Connection.Open()
'cmd.CommandText = "INSERT INTO Orders (OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry) values & OrdersTest.csv"
'cmd.ExecuteNonQuery()
'cmd.Connection.Close()
End Sub
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
' Define the Column Definition
Dim dt As New DataTable()
dt.Columns.Add("OrderID", GetType(Integer))
dt.Columns.Add("CustomerID", GetType(String))
dt.Columns.Add("EmployeeID", GetType(Integer))
dt.Columns.Add("OrderDate", GetType(Date))
dt.Columns.Add("RequiredDate", GetType(Date))
dt.Columns.Add("ShippedDate", GetType(Date))
dt.Columns.Add("ShipVia", GetType(Integer))
dt.Columns.Add("Freight", GetType(Decimal))
dt.Columns.Add("ShipName", GetType(String))
dt.Columns.Add("ShipAddress", GetType(String))
dt.Columns.Add("ShipCity", GetType(String))
dt.Columns.Add("ShipRegion", GetType(String))
dt.Columns.Add("ShipPostalCode", GetType(String))
dt.Columns.Add("ShipCountry", GetType(String))
Using cn = New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
cn.Open()
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
Dim currentRow As String()
Dim dr As DataRow
Dim sqlColumnDataType As String
reader = My.Computer.FileSystem.OpenTextFieldParser("C:\Users\Excel\Desktop\OrdersTest.csv")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
dr = dt.NewRow()
For currColumn = 0 To dt.Columns.Count - 1
sqlColumnDataType = dt.Columns(currColumn).DataType.Name
Select Case sqlColumnDataType
Case "String"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn))
End If
Case "Decimal"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = 0
Else
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn))
End If
Case "DateTime"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn))
End If
End Select
Next
dt.Rows.Add(dr)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid." & vbCrLf & "Terminating Read Operation.")
reader.Close()
reader.Dispose()
'Return False
Finally
dr = Nothing
End Try
End While
Using copy As New SqlBulkCopy(cn)
copy.DestinationTableName = "[dbo].[Orders]"
copy.WriteToServer(dt)
End Using
End Using
End Sub
Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click
'Dim cnn As SqlConnection
'Dim connectionString As String
'Dim sql As String
'connectionString = "data source=Excel-PC\SQLEXPRESS;" & _
'"initial catalog=NORTHWIND;Trusted_Connection=True"
'cnn = New SqlConnection(connectionString)
'cnn.Open()
'GetCsvData("C:\Users\Excel\Desktop\OrdersTest.csv", dbo.Orders)
End Sub
Public Shared Function GetCsvData(ByVal CSVFileName As String, ByRef CSVTable As DataTable) As Boolean
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
Dim currentRow As String()
Dim dr As DataRow
Dim sqlColumnDataType As String
reader = My.Computer.FileSystem.OpenTextFieldParser(CSVFileName)
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
dr = CSVTable.NewRow()
For currColumn = 0 To CSVTable.Columns.Count - 1
sqlColumnDataType = CSVTable.Columns(currColumn).DataType.Name
Select Case sqlColumnDataType
Case "String"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn))
End If
Case "Decimal"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = 0
Else
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn))
End If
Case "DateTime"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn))
End If
End Select
Next
CSVTable.Rows.Add(dr)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid." & vbCrLf & "Terminating Read Operation.")
reader.Close()
reader.Dispose()
Return False
Finally
dr = Nothing
End Try
End While
reader.Close()
reader.Dispose()
Return True
End Function
Private Sub DataGridView1_RowValidating(ByVal sender As Object, ByVal e As DataGridViewCellCancelEventArgs)
End Sub
End Class
One more to try . . .
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim file As String = "Import.txt"
Dim path As String = "C:\Users\path_to_text_file\"
Dim ds As New DataSet
Try
If IO.File.Exists(IO.Path.Combine(path, file)) Then
Dim ConStr As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
path & ";Extended Properties=""Text;HDR=No;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & _
file, conn)
da.Fill(ds, "TextFile")
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class

VB.NET remove strings from an array if exists in another

I want to add items in a ComboBox. I have two array().
Dim purpose_list() As String = {"ADMISSION", "1ST", "2ND", "3RD", "4TH", "5TH", "6TH", "7TH", "8TH", "9TH", "10TH", "11TH", "12TH"}
and
Dim find_purpose = GetListOfPurpose()
The function GetListOfPurpose() is like below..
Private Function GetListOfPurpose() As List(Of String)
Dim Output As New List(Of String)()
Try
OpenConnection()
Dim st_roll As String = TbRoll.Text
Dim c_id As String = CmbCourse.SelectedValue
Dim cmd As New MySqlCommand
Dim qry As String = "SELECT purpose FROM fee_payment WHERE roll_no='" + st_roll + "' AND course='" + c_id + "'"
cmd.Connection = conn
cmd.CommandText = qry
Dim dr As MySqlDataReader = cmd.ExecuteReader
While dr.Read
Output.Add(dr("purpose").ToString())
End While
dr.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
CloseConnection()
End Try
Return Output
End Function
Now I want to find strings in find_purpose and if exists, remove those strings and add the rest into a ComboBox.
Like if find_purpose contains "1ST" and "3RD", the ComboBox will add the rest items
"ADMISSION", "2ND", "4TH", "5TH", "6TH", "7TH", "8TH", "9TH", "10TH", "11TH", "12TH"
I have found This thread but it is in php.
What should I do it in VB.NET ?
The code you posted:
Dim purpose_list() As String = {"ADMISSION", "1ST", "2ND", "3RD", "4TH", "5TH", "6TH", "7TH", "8TH", "9TH", "10TH", "11TH", "12TH"}
Dim find_purpose = GetListOfPurpose()
Private Function GetListOfPurpose() As List(Of String)
Dim Output As New List(Of String)()
Try
OpenConnection()
Dim st_roll As String = TbRoll.Text
Dim c_id As String = CmbCourse.SelectedValue
Dim cmd As New MySqlCommand
Dim qry As String = "SELECT purpose FROM fee_payment WHERE roll_no='" + st_roll + "' AND course='" + c_id + "'"
cmd.Connection = conn
cmd.CommandText = qry
Dim dr As MySqlDataReader = cmd.ExecuteReader
While dr.Read
Output.Add(dr("purpose").ToString())
End While
dr.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
CloseConnection()
End Try
Return Output
End Function
Now, in an Event-Handling Sub (or wherever you would like to do the checking) put this code:
Dim final_list As New List(Of String)
For Each item In purpose_list
If Not(find_purpose.Contains(item)) Then
final_list.Add(item)
End If
Next
ComboBox1.Items.AddRange(final_list.ToArray())

How to prevent array from adding (sum) together

I have an array. My program goes through and sets up the array. However, when I display the array,it's adding the arrays together.
Here is my code:
Public Class frmMain
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim yPoint As Integer
Dim LocationDB As String
Dim dtstartdate As Date
Dim dtenddate As Date
Dim LocationName As String
Dim BookSales(17) As Integer
Public Shared locationcounter As Integer
Dim i As Integer
Public Sub Get_Info()
If locationcounter < 18 Then
dtstartdate = dtpStartDate.Value
dtenddate = dtpEndDate.Value.AddDays(1).AddSeconds(-1)
Try
connetionString = "Data Source=" & LocationDB & ";Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=test"
sql = "Select * from fGetdata"
connection = New SqlConnection(connetionString)
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.SelectCommand.CommandTimeout = 130
adapter.SelectCommand.Parameters.AddWithValue("#StartDate", dtstartdate)
adapter.SelectCommand.Parameters.AddWithValue("#EndDate", dtenddate)
adapter.Fill(ds)
connection.Close()
connection.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try
For Each FoundRow As DataRow In ds.Tables(0).Rows
Select Case FoundRow("CategoryName")
Case "TOTAL"
Select Case FoundRow("Description")
Case "BOOK", "BOOK SALES", "GC"
BookSales(i) = BookSales(i) + (FoundRow("netAmt"))
End Select
End Select
Next
MsgBox(LocationName & BookSales(i))
MsgBox(LocationName & BookSales(0))
MsgBox(LocationName & BookSales(1))
End If
End Sub
Public Sub GetLocation()
Select Case locationcounter
Case "1"
LocationName = "Location1"
Locationdb = "10.0.1.52"
Case "2"
LocationName = "Location2"
Locationdb = "10.0.1.51"
Case "3"
LocationName = "Location3"
Locationdb = "10.0.1.50"
End Select
End Sub
Button Click:
For x = 1 To 3
GetLocation()
Label1.Text = LocationName
Label1.Refresh()
Get_Info()
i = i + 1
locationcounter = locationcounter + 1
Next
I am getting:
Location1 5
Location2 25
Location3 35
I would like to get:
Location1 5
Location2 20
Location3 10
For some reason the arrays are adding together
As you noted, the problem is that the DataSet was getting reused so it accumulated the results on each loop.
You need to clean up the coding style. Put things in as tight of scope as possible. In this case all the vars used by the Get_Info() method should be declared within the method. This prevents side effects from long living variables. The DataSet is only used in the Get_Info method so it should only exist there.
Clean up the resources in a Finally block. In the example below I moved the connection.Dispose into the finally block. You only need to call Dispose, you don't need the Close also.
You should also enable Option Strict and Option Explicit. These will help prevent casing errors that don't show up until runtime. As an example of type mismatch, you declare the loctioncounter as integer but use it as a string in the GetLocation method.
There are more but this should get you started in the right direction.
Public Class frmMain
Dim yPoint As Integer
Dim LocationDB As String
Dim dtstartdate As Date
Dim dtenddate As Date
Dim LocationName As String
Dim BookSales(17) As Integer
Public Shared locationcounter As Integer
Dim i As Integer
Public Sub Get_Info()
Dim connetionString As String
Dim connection As SqlConnection = Nothing
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
If locationcounter < 18 Then
dtstartdate = dtpStartDate.Value
dtenddate = dtpEndDate.Value.AddDays(1).AddSeconds(-1)
Try
connetionString = "Data Source=" & LocationDB & ";Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=test"
sql = "Select * from fGetdata"
connection = New SqlConnection(connetionString)
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.SelectCommand.CommandTimeout = 130
adapter.SelectCommand.Parameters.AddWithValue("#StartDate", dtstartdate)
adapter.SelectCommand.Parameters.AddWithValue("#EndDate", dtenddate)
adapter.Fill(ds)
For Each FoundRow As DataRow In ds.Tables(0).Rows
Select Case FoundRow("CategoryName")
Case "TOTAL"
Select Case FoundRow("Description")
Case "BOOK", "BOOK SALES", "GC"
BookSales(i) = BookSales(i) + (FoundRow("netAmt"))
End Select
End Select
Next
MsgBox(LocationName & BookSales(i))
MsgBox(LocationName & BookSales(0))
MsgBox(LocationName & BookSales(1))
Catch ex As Exception
MsgBox(ex.Message)
Finally
If connection IsNot Nothing Then
connection.Dispose()
End If
End Try
End If
End Sub
Public Sub GetLocation()
Select Case locationcounter
Case "1"
LocationName = "Location1"
LocationDB = "10.0.1.52"
Case "2"
LocationName = "Location2"
LocationDB = "10.0.1.51"
Case "3"
LocationName = "Location3"
LocationDB = "10.0.1.50"
End Select
End Sub

Resources