How can I combine two datagridview? - vb.net

I'm new to VB.net. I want to combine two datagridviews, I get those two data from a CSV file. For example I have Datagridview1:
Dim sr As System.IO.StreamReader = Nothing
Dim dt As New DataTable
Try
readFileName = "LNU010F" & "_" & dateParam.ToString("MM-dd-yyyy") & ".csv"
sr = New System.IO.StreamReader("C:\Documents and Settings\ucpb\Desktop\Sample CSV data\" + readFileName)
Dim newline() As String = sr.ReadLine.Split("|"c)
dt.Columns.AddRange({New DataColumn(newline(11)), New DataColumn(newline(48))})
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split("|"c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(11), newline(48)}
dt.Rows.Add(newrow)
End While
DataGridViewCSV1.DataSource = dt
This is what I get from the first code.
http://i.stack.imgur.com/QaJZ1.png
I have Datagridview2:
Dim delimeter As String = txtDelimiter.Text
Dim fileReader As System.IO.StreamReader = Nothing
Dim dt As New DataTable
Try
fileName = txtName.Text & "_" & dateParam.ToString("MM-dd-yyyy")
readFileName = txtName.Text & "_" & dateParam.ToString("MM-dd-yyyy") & ".csv"
fileReader = New System.IO.StreamReader("C:\Documents and Settings\ucpb\Desktop\Sample CSV data\" + readFileName)
Dim readColumn As String = fileReader.ReadLine
Dim splitColumn As String() = readColumn.Split(delimeter)
For Each arr As String In splitColumn
dt.Columns.Add(arr)
Next
Dim readRow As String = fileReader.ReadLine
Dim splitRow As String()
While readRow <> ""
splitRow = readRow.Split(delimeter)
dt.Rows.Add(splitRow)
readRow = fileReader.ReadLine()
End While
DataGridViewCSV2.DataSource = dt
This is what I get from the second code.
http://i.stack.imgur.com/r0SmT.png
What I want is to add the UID(Datagridview1) at the end of the Datagridview2. Acctno is the key, Datagridview2 should have the same UID as in the first datagridview because the data is not properly arranged in the datagridview2. Any answer would be appreciated. Thank you.

Related

SSIS Create and Attaching file to the email

I've 2 sqlreaders and both should loop through it and second sqlreader data should create a table and inserting into the excel sheet.
Lets say
I've sqlreader and sqlreader1
sqlreader has some data which is required to get sqlreader1
I'm able to get sqlreader1 data as I expected
but once I loaded data to datatable, I'm loosing sqlreader1 and not able to see any info in sqlreader1
If SqlDataReader.HasRows Then
Do While SqlDataReader.Read()
Dim ExcelFileName As String = Dts.Variables("User::FolderPath").Value.ToString() + "Accrual_Input_Summary_Q" + SqlDataReader.Item("Accrual_Quarter").ToString() + " FY-" + SqlDataReader.Item("Accrual_FY").ToString() + ".xlsx"
'Dim recipientName As String = SqlDataReader.Item("recipient_name").ToString()
'Dim recipientEmail As String = SqlDataReader.Item("Recipient_Email").ToString()
Try
If System.IO.File.Exists(ExcelFileName) = True Then
System.IO.File.Delete(ExcelFileName)
End If
Dim SqlCmd1 As New SqlCommand("[POT].[PROC_POT_Accrual_Reminder_Summary]", SqlCon)
SqlCmd1.CommandType = CommandType.StoredProcedure
SqlCmd1.CommandTimeout = 0
SqlCmd1.Parameters.AddWithValue("#Qtype", "Accrual_Summary")
SqlCmd1.Parameters.AddWithValue("#Accrual_Created_By_Email", SqlDataReader.Item("Recipient_Email").ToString())
Dim SqlDataReader1 As SqlDataReader = SqlCmd1.ExecuteReader()
' connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" &
'"Data Source=" & ExcelFileName &
'";Extended Properties=Excel 12.0 Xml;HDR=YES;"
If SqlDataReader1.HasRows Then
While SqlDataReader1.Read()
Dim connectionString As String
Dim excelConnection As OleDbConnection
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & ExcelFileName & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES;"""
excelConnection = New OleDbConnection(connectionString)
Dim Excel_OLE_Cmd As OleDbCommand = New OleDbCommand()
Dim recipientName As String = SqlDataReader1.Item("Created_By_Name").ToString()
Dim recipientEmail As String = SqlDataReader1.Item("CostCenterAnalyst").ToString()
Dim costCenterOwner As String = SqlDataReader1.Item("CostCenterOwner").ToString()
Dim TableColumns As String = ""
Dim dtCustomers As New DataTable("sqlDataTable")
**dtCustomers.Load(SqlDataReader1)**
For Each column As DataColumn In dtCustomers.Columns
TableColumns += column.ToString() & "],["
Next
TableColumns = ("[" & TableColumns.Replace(",", " Text,").TrimEnd(","c))
TableColumns = TableColumns.Remove(TableColumns.Length - 2)
excelConnection.ConnectionString = connectionString
excelConnection.Open()
Excel_OLE_Cmd.Connection = excelConnection
Excel_OLE_Cmd.CommandText = "Create table " & "Sheet1" & " (" & TableColumns & ")"
Excel_OLE_Cmd.ExecuteNonQuery()
Dim sqlCommandInsert As String = ""
Dim sqlCommandValue As String = ""
For Each dataColumn As DataColumn In dtCustomers.Columns
sqlCommandValue += dataColumn.ToString() & "],["
Next
sqlCommandValue = "[" & sqlCommandValue.TrimEnd(","c)
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2)
sqlCommandInsert = "INSERT into " & "Sheet1" & "(" & sqlCommandValue & ") VALUES("
Dim columnCount As Integer = dtCustomers.Columns.Count
For Each row As DataRow In dtCustomers.Rows
Dim columnvalues As String = ""
For i As Integer = 0 To columnCount - 1
Dim index As Integer = dtCustomers.Rows.IndexOf(row)
columnvalues += "'" & dtCustomers.Rows(index).ItemArray(i).ToString() & "',"
Next
columnvalues = columnvalues.TrimEnd(","c)
Dim command As String = sqlCommandInsert & columnvalues & ")"
Excel_OLE_Cmd.CommandText = command
Excel_OLE_Cmd.ExecuteNonQuery()
Next
excelConnection.Close()
StrMailBody_Inner = " Hello Cost Center Analyst (" & recipientName & "), <br/><br/> PFA accrual inputs for the current quarter. Please review & take appropriate action click <a href='http://podashboarddev/' target='_blank'>here</a>.<br/><br/>"
StrMailBody_Inner = StrMailBody_Inner + " <u>Note</u><br/>"
StrMailBody_Inner = StrMailBody_Inner + " <ol>"
StrMailBody_Inner = StrMailBody_Inner + " <li>The accrual inputs provided doesn't interface with SAP. You will still need to post the necessary accrual JV.</li>"
StrMailBody_Inner = StrMailBody_Inner + " <li>CCA can leverage the tool for accrual tracking.</li>"
StrMailBody_Inner = StrMailBody_Inner + " </ol>"
Using myMessage As New MailMessage(Dts.Variables("email_from").Value, recipientEmail)
Dim copy As MailAddress = New MailAddress(costCenterOwner)
myMessage.CC.Add(copy)
myMessage.IsBodyHtml = True
myMessage.Subject = Dts.Variables("email_subject").Value
myMessage.Body = StrMailBody.ToString().Replace("$$$$Mail_Body$$$$", StrMailBody_Inner)
myMessage.Priority = System.Net.Mail.MailPriority.High
myMessage.Attachments.Add(New Attachment(ExcelFileName))
mySmtpClient = New SmtpClient("mailserver.amat.com")
mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
'mySmtpClient.Send(myMessage)
Dim str_SQL As String
str_SQL = "INSERT INTO [POT].[tbl_POT_Open_PO_Accrual_Reminder_History] ([Recipient_Email], [Reminder_Type]) VALUES ('" + SqlDataReader.Item("recipient_email").ToString() + "', 'Accrual_Summary');"
Dim SqlCmdHist As New SqlCommand(str_SQL, SqlCon)
SqlCmdHist.CommandType = CommandType.Text
SqlCmdHist.CommandTimeout = 0
SqlCmdHist.ExecuteNonQuery()
SqlCmdHist.Dispose()
End Using
End While
SqlDataReader1.Close()
End If
Once I load data to Datatable using this
dtCustomers.Load(SqlDataReader1)
before load data:
after load data:
I'm missing the sqlreader1 and i'm unable to loop through it.
it is giving Invalid attempt to call Read when reader is closed.
Note: I've enabled MultipleActiveResultSets
can we do any other things that we can do to resolve this issue

Visual Basic write text file adds an extra line feed

I have a visual basic application where I read in an excel spreadsheet and write the contents to a .csv file. The application works as expected however there appears to be an extra line feed generated at the end of each line. This is the code I am executing:
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox1.Visible = True
Dim fileName As String = OpenFileDialog1.FileName.ToString()
Dim sPath As String = StrReverse(fileName) 'reverse the string
sPath = Mid(sPath, InStr(sPath, "\"), Len(sPath)) 'extract from the first slash
sPath = StrReverse(sPath) 'reverse it again
Dim xlsFileFolder As String = sPath
Dim xlsFileName As String = Path.GetFileName(fileName)
Dim csvFileName As String = Path.GetFileNameWithoutExtension(fileName) + ".csv"
Dim csfFileNameAndPath As String = xlsFileFolder + csvFileName
If Not (strm Is Nothing) Then
Dim di As New IO.DirectoryInfo(xlsFileFolder)
Dim aryFi As IO.FileInfo() = di.GetFiles(xlsFileName)
Dim ds As New DataSet
Dim workbook As IWorkbook
Dim worksheet As ISheet
Dim sheetCount As Integer
Dim file = New FileStream(fileName, FileMode.Open, FileAccess.Read)
workbook = New HSSFWorkbook(file)
sheetCount = workbook.NumberOfSheets
Dim table As New DataTable
worksheet = workbook.GetSheetAt(0)
Dim numberOfDataRecords = worksheet.PhysicalNumberOfRows
Dim numberOfColumns = worksheet.GetRow(0).PhysicalNumberOfCells
Dim dataRow As Integer = 0
Dim dataColumn As Integer = 0
Dim quote As String = """"
Dim cellData As String = ""
Using writer As StreamWriter = New StreamWriter(csfFileNameAndPath)
For dataRow = 0 To numberOfDataRecords - 1
Dim csvLine As String = quote
For dataColumn = 0 To numberOfColumns - 1
cellData = worksheet.GetRow(dataRow).GetCell(dataColumn).ToString()
cellData = cellData.Replace(quote, "'")
csvLine = csvLine + cellData + quote + "," + quote
Next
Dim l As Integer = csvLine.Length - 2
csvLine = Microsoft.VisualBasic.Left(csvLine, l)
csvLine = csvLine + vbCr
writer.WriteLine(csvLine)
Next
End Using
TextBox1.Text = "Done!"
End If
End Sub
This is an image of the selected excel file:
And this is an image of the resulting .csv file:
As you can see, there is a blank line being generated after each line of text in the .csv file.
Any assistance is greatly appreciated.
Thanks!
Remove this line and you should be fine. csvLine = csvLine + vbCr

Download multiple files from Web

I am working on some application to download files of stock prices for different dates from url. I am using the following code
Conn = New OdbcConnection("DSN=RA;MultipleActiveResultSets=True")
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
Dim mont As Date
mont = DateTimePicker1.Value
Dim dnldurlA As String = "http://www.nseindia.com/content/historical/EQUITIES/"
Dim dnldurlB As String = UCase(mont.ToString("MMM"))
Dim dnldurlC As String = "/"
Dim dnldurlD As String = "cm"
Dim dnldurlE As String = mont.ToString("dd")
Dim dnldurlF As String = mont.ToString("yyyy")
Dim dnldurlG As String = "bhav"
Dim dnldurlH As String = ".csv"
Dim dnldurlI As String = ".zip"
Dim dnldurlJ As String = "\"
Dim FileName As String = dnldurlE & dnldurlB & dnldurlF & ".ZIP"
Try
Dim downloadClient As New WebClient()
downloadClient.Headers("Accept") = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
downloadClient.Headers("User-Agent") = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1"
Dim dnldurl As String = dnldurlA & dnldurlF & dnldurlC & dnldurlB & dnldurlC & dnldurlD & dnldurlE & dnldurlB & dnldurlF & dnldurlG & dnldurlH & dnldurlI
downloadClient.DownloadFile(New Uri(dnldurl), ("C:\" & FileName))
While (downloadClient.IsBusy = True)
End While
downloadClient.Dispose()
Catch ex As Exception
MsgBox("File can not be downloaded!!!")
Me.Close()
End Try
I am stuck with after downloading the first file, when I selected the file for another date, it throws an error
{"The remote server returned an error: (403) Forbidden."}
But when I exit the application and try again for the same date, the file is downloaded promptly.
Please help
Thanks in advance
Kris
I just made a small change and it worked perfectly
Conn = New OdbcConnection("DSN=RA;MultipleActiveResultSets=True")
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
Dim mont As Date
mont = DateTimePicker1.Value
Dim dnldurlA As String = "http://www.nseindia.com/content/historical/EQUITIES/"
Dim dnldurlB As String = UCase(mont.ToString("MMM"))
Dim dnldurlC As String = "/"
Dim dnldurlD As String = "cm"
Dim dnldurlE As String = mont.ToString("dd")
Dim dnldurlF As String = mont.ToString("yyyy")
Dim dnldurlG As String = "bhav"
Dim dnldurlH As String = ".csv"
Dim dnldurlI As String = ".zip"
Dim dnldurlJ As String = "\"
Dim FileName As String = dnldurlE & dnldurlB & dnldurlF & ".ZIP"
Try
Dim downloadClient As New WebClient()
Dim dnldurl As String = dnldurlA & dnldurlF & dnldurlC & dnldurlB & dnldurlC & dnldurlD & dnldurlE & dnldurlB & dnldurlF & dnldurlG & dnldurlH & dnldurlI
downloadClient.DownloadFile(New Uri(dnldurl), ("C:\" & FileName))
While (downloadClient.IsBusy = True)
End While
downloadClient.Dispose()
Catch ex As Exception
MsgBox("File can not be downloaded!!!")
Me.Close()
End Try
Thanks

Read a text file which contains SQL code to create tables in a database

I need code to read a .txt file which is in my project bin\debug directory that contains SQL code to create tables in a large number it size of 936kb
This following code only I'm using...
By using this it gives result like table created but it is not reading the file... there is nothing in the database
Public Function readTextFile(ByVal fileName As String) As String
Dim strContent As String()
Dim x As String = ""
Try
'fileName = "CSYSS802.txt"
If Not System.IO.File.Exists(fileName) Then
'o Until EOF()
strContent = System.IO.File.ReadAllLines(fileName)
For Each Str As String In strContent
x = x + Str
Next
readTextFile = x
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
readTextFile = x
End Function
Public Sub createTable(ByVal vdbs As String, ByVal file As String)
username = frmlogin.txtusername.Text
password = frmlogin.txtusername.Text
vsvr = vServer
vdb = Trim$(vdbs)
strCon1 = "Server=" & vsvr & ";Database=" & vdb & ";uid=" & username & ";pwd=" & password & ";"
sqlCon1 = New SqlClient.SqlConnection(strCon1)
sqlCon1.Open()
Dim arr() As String
arr = Split(readTextFile(file), "GO")
Dim i As String
For Each i In arr
If i <> "" Then
Dim cmd2 As New SqlClient.SqlCommand("" & i & "")
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
End If
Next
End Sub
In the readTextFile function, it will only attempt to read the text from the text file if the file DOESN'T exist. If the text file exists then the function returns an empty string and if the text file doesn't exist, the function will throw a file not found exception.
Replace:
If Not System.IO.File.Exists(fileName) Then
with:
If System.IO.File.Exists(fileName) = True Then
You might also want to include an Else clause in case the file doesn't exist as it won't throw an error since you have handled it correctly.
If System.IO.File.Exists(fileName) = True Then
strContent = System.IO.File.ReadAllLines(fileName)
For Each Str As String In strContent
x &= Str
Next
Return x
Else
MessageBox.Show("The file '" & fileName & "' does not exist.")
Return ""
End If
My Self I had Found The solution..I attache the Following Code...It now Creating All tables Properly..
Make sure that each Sql Commands in your Text File ends with go.. because i used "GO" Keyword to split the text...
Public Sub createTable(ByVal vdbs As String, ByVal file As String)
username = frmlogin.txtusername.Text
password = frmlogin.txtusername.Text
vsvr = vServer
vdb = Trim$(vdbs)
strCon1 = "Server=" & vsvr & ";Database=" & vdb & ";uid=" & username & ";pwd=" & password & ";"
sqlCon1 = New SqlClient.SqlConnection(strCon1)
sqlCon1.Open()
Dim arr() As String
arr = Split(readTextFile(file), " GO ")
Dim i As String
For Each i In arr
If i <> "" Then
Dim cmd2 As New SqlClient.SqlCommand("" & i & "", sqlCon1)
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
End If
Next
End Sub
Public Function readTextFile(ByVal file As String) As String
Dim fso As New System.Object
Dim ts As Scripting.TextStream
Dim sLine As String
fso = CreateObject("Scripting.FileSystemObject")
ts = fso.openTextFile(file)
Do Until ts.AtEndOfStream
sLine = sLine & " " & ts.ReadLine
Loop
ts.Close()
fso = Nothing
readTextFile = sLine
End Function

How to Request a File from FTP Using Today's Date as part of Filename?

We have a service that provides several files per day for pickup. Each file is appended with today's date and the hours, minutes, seconds and milliseconds stamp of the time the file was created.
Our goal is to download all files for a given day regardless of the time stamp. I've set the following variable:
Dim remoteFile As String = "/datafeed/sdlookup-total-" & DateTime.Today.Year.ToString
& "-" & DateTime.Today.Month.ToString("0#") & "-" & DateTime.Today.Day.ToString("0#") &
".csv.zip"
When I run the console application, I receive a HTTP 550 file not found because the files on the FTP all have the timestamp after the day e.g.
sdlookup-total-2013-07-27_02_15_00_272.csv.zip
The Module is as follows:
Imports System.IO
Imports System.IO.Compression
Imports System.Net
Imports System.Net.WebClient
' This module when run will download the file specified and save it to the local path as defined.
Module Module1
Dim Today As Date = Now()
' Change the value of localFile to the desired local path and filename
Dim localFile As String = "C:\ForeclosureFile\sdlookoup-total-" & Today.Year.ToString & "-" &
Today.Month.ToString("0#") & "-" & Today.Day.ToString("0#") & ".csv.zip"
' Change the value of remoteFile to the desired filename
Dim remoteFile As String = "/datafeed/sdlookup-total-" & Today.Year.ToString & "-" &
Today.Month.ToString("0#") & "-" & Today.Day.ToString("0#") & ".csv.zip"
Const host As String = "ftp://Datafeed.foreclosure.com"
Const username As String = "sdlookup"
Const pw As String = "ourpass"
Dim strDownLoadTemplate = "sdlookup-total-" & Today.Year.ToString & "-" & Today.Month.ToString
("0#") & "-" & Today.Day.ToString("0#") & ".csv.zip"
Dim strCleanFileForDTS As String
Dim strLocalZipFile = "C:\ForeclosureFile\ForeclosureFull.zip"
Dim strLocalCSVFile = "C:\ForeclosureFile\Foreclosurefull.csv"
Sub Main()
Dim URI As String = host + remoteFile
Dim req As FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)
req.Credentials = New NetworkCredential(username, pw)
req.KeepAlive = False
req.UseBinary = True
req.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
Using response As System.Net.FtpWebResponse = CType(req.GetResponse,
System.Net.FtpWebResponse)
Using responseStream As IO.Stream = response.GetResponseStream
Using fs As New IO.FileStream(localFile, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
End Using
Dim zipPath As String = "C:\ForeclosureFile\"
Dim extractPath As String = "C:\ForeclousreFile"
ZipFile.ExtractToDirectory(zipPath, extractPath)
End Sub
Sub ProcessFile()
'Downloaded file
Dim oFile As System.IO.File
Dim oRead As System.IO.StreamReader
Dim strLocalCSVFile As String = "C:\ForeclosureFile\sdlookoup-total-" &
DateTime.Today.Year.ToString & "-" & DateTime.Today.Month.ToString("0#") & "-" &
DateTime.Today.Day.ToString("0#") & ".csv"
Dim strCleanFileForDTS As String = "C:\ForeclosureFile\ForDTS\sdlookoup-total-" &
DateTime.Today.Year.ToString & "-" & DateTime.Today.Month.ToString("0#") & "-" &
DateTime.Today.Day.ToString("0#") & ".csv"
Dim LineIn As String
'Dim Fields() As String
'New File
Dim oNewFile As System.IO.File
Dim oWrite As System.IO.StreamWriter
oWrite = File.CreateText(localFile & strCleanFileForDTS)
oRead = File.OpenText(localFile & strLocalCSVFile)
' strLocalCSVFile()
While oRead.Peek <> -1
'While oRead.
LineIn = oRead.ReadLine()
'Fixes file problem
oWrite.WriteLine(Replace(LineIn, """", "", 1))
End While
oRead.Close()
oWrite.Close()
End Sub
Sub FTPFileDownload(strtFetchFile As String, PathToSave As String)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
Dim myStreamWriter As StreamWriter
Dim strFullPathandFile As String
strFullPathandFile = PathToSave & strtFetchFile
myFtpWebRequest = WebRequest.Create("ftp://Datafeed.foreclosure.com/datafeed/" &
strtFetchFile)
myFtpWebRequest.Credentials = New NetworkCredential("sdlookup", "ohpaiH1b")
myFtpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile
myFtpWebRequest.UseBinary = True
myFtpWebRequest.UsePassive = True
myFtpWebResponse = myFtpWebRequest.GetResponse()
PathToSave = "D:\test.zip"
myStreamWriter = New StreamWriter(PathToSave)
myStreamWriter.Write(New StreamReader(myFtpWebResponse.GetResponseStream()).ReadToEnd)
myStreamWriter.Close()
' litResponse.Text = myFtpWebResponse.StatusDescription
myFtpWebResponse.Close()
End Sub
Public Sub DownloadFiles(ByVal Wildcard As String)
Wildcard = "sdlookup-total-*.csv.zip"
Dim Files As String() = GetFiles(Wildcard)
For Each file As String In Files
DownloadFile(file)
Next
End Sub
End Module
How should I modify the above module so that all files containing sdlookup-total-"Today'sDate".csv.zip regardless of timestamp are downloaded each time the module is executed?