Attachment from Datagridview VB.NET - vb.net

Can someone tell me is it correct now , how to read files from Datagridview in attachment.
I need to fetch the items from the datagridview and add them in the email attachment.
How i can fetch them?
How can i manage it in function SendMail() to support it?
Public Sub SendMail()
Dim oEmail As MailItem = CType(New Application().CreateItem(OlItemType.olMailItem), MailItem)
oEmail.Recipients.Add("emailTo") 'Send TO
oEmail.CC = "CopyEmail" 'Send CC
oEmail.Recipients.ResolveAll()
oEmail.Subject = "Spam - Meow!"
oEmail.BodyFormat = OlBodyFormat.olFormatHTML
oEmail.Body = "Blah, blah, blah..."
oEmail.Importance = OlImportance.olImportanceNormal 'Request read email confirmation
oEmail.ReadReceiptRequested = True
**If DataGridView1.Rows.Count > 0 Then
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells("Name").Tag IsNot Nothing Then
Dim MsgAttach As New Attachment(CStr(row.Cells("Name").Tag))
oEmail.Attachments.Add(MsgAttach)
End If
Next
End If**
oEmail.Recipients.ResolveAll()
oEmail.Save()
oEmail.Display(False) 'Show the email message and allow for editing before sending
oEmail.Send() 'You can automatically send the email without displaying it.
End Sub
Button Browse:
OpenFileDialog1.FileName = "Folder1"
OpenFileDialog1.DefaultExt = "*.*"
OpenFileDialog1.FilterIndex = 6
OpenFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
OpenFileDialog1.Multiselect = True
Dim saveDirectory As String = ".\Files\"
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
If Not Directory.Exists(saveDirectory) Then
Directory.CreateDirectory(saveDirectory)
End If
For Each item As String In OpenFileDialog1.FileNames
Dim fileName As String = Path.GetFileName(OpenFileDialog1.FileName)
Dim fileSavePath As String = Path.Combine(saveDirectory, fileName)
File.Copy(OpenFileDialog1.FileName, fileSavePath, True)
Next
End If
BindDataGrid()
Private Sub BindDataGrid()
Dim filePaths As String() = Directory.GetFiles(".\Files\")
Dim dt As DataTable = New DataTable()
dt.Columns.Add("Text")
dt.Columns.Add("Value")
For Each filePath As String In filePaths
dt.Rows.Add(IO.Path.GetFileName(filePath), filePath)
Next
dataGridView1.AllowUserToAddRows = False
dataGridView1.Columns.Clear()
Dim name As DataGridViewColumn = New DataGridViewTextBoxColumn With {
.Name = "Name",
.HeaderText = "File Name",
.DataPropertyName = "Text",
.Width = 100
}
DataGridView1.Columns.Insert(0, name)
Dim path As DataGridViewColumn = New DataGridViewTextBoxColumn With {
.Name = "Path",
.HeaderText = "File Path",
.DataPropertyName = "Value",
.Width = 100
}
DataGridView1.Columns.Insert(1, path)
DataGridView1.DataSource = dt
Dim buttonColumn As DataGridViewButtonColumn = New DataGridViewButtonColumn With {
.HeaderText = "",
.Width = 60,
.Name = "buttonColumn",
.Text = "Delete",
.UseColumnTextForButtonValue = True
}
DataGridView1.Columns.Insert(2, buttonColumn)
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.ColumnIndex = 2 Then
Dim row As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
If MessageBox.Show(String.Format("Do you want to delete Name:{0}?", row.Cells("Name").Value), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
File.Delete(row.Cells("Path").Value.ToString())
BindDataGrid()
End If
End If
End Sub
How can i get from datagridview the items to attach it to email?

Related

How to import .csv file to my datagridview in vb.net?

My used code is:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "c:\desktop"
OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
txtpathfile.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView2.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If
End Sub
My output looks wrongly encoded:
What's wrong with my code? Please help me. Thank you for consideration.
I arrived here from google. Just in case someone sarching for a quick code to copy:
Private Sub ReadCSV()
Dim fName As String = "C:\myfile.csv"
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(fName) = True Then
Using objReader As New System.IO.StreamReader(fName, Encoding.ASCII)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ";")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
End Using
Else
MsgBox("File Does Not Exist")
End If
End Sub
For anyone that has been looking for other solution, this works and let me add, delete and update the same datagrid without any problem
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using ofd As OpenFileDialog = New OpenFileDialog()
If ofd.ShowDialog() = DialogResult.OK Then
file_path.Text = ofd.FileName
Dim lines As List(Of String) = File.ReadAllLines(ofd.FileName).ToList()
Dim list As List(Of User) = New List(Of User)
fill_Columns(lines)
For i As Integer = 1 To lines.Count - 1
Dim data As String() = lines(i).Split(",")
addElements(
data(0),
data(1),
data(2),
data(3),
data(4)
) 'All this elements has to match with the -fill_Columns- elements
Next
End If
End Using
End Sub
Use it on the button where you want to click it... Also add this
Private Sub fill_Columns(lines As List(Of String))
Dim columns() As String = lines(0).Split(",")
For Each item In columns
Dim col As New DataGridViewTextBoxColumn
col.HeaderText = item
col.Name = item
col.DataPropertyName = item
DataGridView1.Columns.Add(col)
Next
End Sub
Private Sub addElements(Code As String, Name As String, Birth As DateTime, Email As String, Address As String)
DataGridView1.Rows.Add(
Code,
Name,
Birth.ToString,
Email,
Address
) 'You add or delete as you need
End Sub
This is really work!
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "c:\desktop"
OpenFileDialog1.Filter = "CSV files(*.csv)|*.csv"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
txtpathfile.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(txtpathfile.Text, Encoding.ASCII)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ";")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If

Attaching a screenshot to new email outlook image with vb net

been looking for a bit of code to take a screenshot and attach the screenshot to new email. I'll post what I have. It work 99%, just can't for the life of me figure out why it isn't attaching to the email.
It does everything but attach the new screenshot to the email. Is this possible?
Private Sub testStripMenuItem_Click(sender As Object, e As EventArgs) Handles testStripMenuItem.Click
Dim maxHeight As Integer = 0
Dim maxWidth As Integer = 0
For Each scr As Screen In Screen.AllScreens
maxWidth += scr.Bounds.Width
If scr.Bounds.Height > maxHeight Then maxHeight = scr.Bounds.Height
Next
Dim AllScreensCapture As New Bitmap(maxWidth, maxHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb)
Dim screenGrab As Bitmap
Dim screenSize As Size
Dim g As Graphics
Dim g2 As Graphics = Graphics.FromImage(AllScreensCapture)
Dim a As New Point(0, 0)
For Each scr As Screen In Screen.AllScreens
screenSize = New Size(scr.Bounds.Width, scr.Bounds.Height)
screenGrab = New Bitmap(scr.Bounds.Width, scr.Bounds.Height)
g = Graphics.FromImage(screenGrab)
g.CopyFromScreen(a, New Point(0, 0), screenSize)
g2.DrawImage(screenGrab, a)
a.X += scr.Bounds.Width
Next
Dim Screenshot = "C:\img.png"
If System.IO.File.Exists(Screenshot) Then
System.IO.File.Delete(Screenshot)
End If
AllScreensCapture.Save(Screenshot, System.Drawing.Imaging.ImageFormat.Jpeg)
'Email Code
Dim strUserDomain As String
Dim strCompName As String
strUserDomain = Environ$("UserDomain")
strCompName = Environ$("ComputerName")
Dim theStringBuilder As New StringBuilder()
theStringBuilder.Append("mailto:email#gmail.com.au")
theStringBuilder.Append("&subject=From Domain: " & strUserDomain & ". Computer Name: " & strCompName)
theStringBuilder.Append("&attach=" & Screenshot)
Process.Start(theStringBuilder.ToString())
End Sub
Alternative to sending through an installed mail client...
' Some of these may come from the form or user settings or wherever
Private Const MailSenderEmail As String = ""
Private Const MailSenderName As String = ""
Private Const MailRecipient As String = ""
Private Const MailSubject As String = ""
Private Const MailBody As String = ""
Private Const MailHost As String = ""
Private Const MailPort As String = ""
Private Const MailUser As String = ""
Private Const MailPass As String = ""
Private Const MailEnableSsl As Boolean = False
Private Sub testStripMenuItem_Click(sender As Object, e As EventArgs) Handles testStripMenuItem.Click
'
' Your code to capture the screen
'
Dim Screenshot = "C:\img.png"
If System.IO.File.Exists(Screenshot) Then
System.IO.File.Delete(Screenshot)
End If
AllScreensCapture.Save(Screenshot, System.Drawing.Imaging.ImageFormat.Jpeg)
' Send the email with Screenshot attached
Using MailMessage As New Net.Mail.MailMessage
With MailMessage
.From = New Net.Mail.MailAddress(MailSenderEmail, MailSenderName)
.To.Add(MailRecipient)
.Subject = MailSubject
.Body = MailBody
.Attachments.Add(New Net.Mail.Attachment(Screenshot))
End With
With New Net.Mail.SmtpClient
.Host = MailHost
.Port = MailPort
.EnableSsl = MailEnableSsl
Select Case True
Case String.IsNullOrWhiteSpace(MailUser)
Case String.IsNullOrWhiteSpace(MailPass)
Case Else
.Credentials = New Net.NetworkCredential(MailUser, MailPass)
End Select
.Send(MailMessage)
End With
End Using
End Sub

VB2010 read a csv in datagrid, update in grid and save to same csv

Created a procedure in VB2010 to read a csv-file in datagridviewer, update cells in grid and save to same csvfile
Opening the csvfile in the datagridviewer works fine,
Updating in the datagridviewer works fine also
But when I save the datagrid to a csv-file with the same name, I get an error message "The process Can not access the file because it is used by an other process".
But if I save it to an other filename it is ok.
Then I tried to copy the new file with the new filename back to the original filename.
I received still the same error message that I cant copy because the file is still in use.
Does anybody now how to solve this.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "H:\Data\2014\Software\VB2010\"
OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
Me.TextBox1.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
DataGridView1.ColumnCount = 5
DataGridView1.Columns(0).Name = "Name"
DataGridView1.Columns(1).Name = "Gender"
DataGridView1.Columns(2).Name = "Age"
DataGridView1.Columns(3).Name = "Ranking"
DataGridView1.Columns(4).Name = "Date"
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If
End Sub
Private Sub SaveGridDataInFile(ByRef fName As String)
'method called by button2
Dim I As Integer = 0
Dim j As Integer = 0
Dim cellvalue$
Dim rowLine As String = ""
Try
Dim objWriter As New System.IO.StreamWriter(fName, True)
For j = 0 To (DataGridView1.Rows.Count - 2)
For I = 0 To (DataGridView1.Columns.Count - 1)
If Not TypeOf DataGridView1.CurrentRow.Cells.Item(I).Value Is DBNull Then
cellvalue = DataGridView1.Item(I, j).Value
Else
cellvalue = ""
End If
rowLine = rowLine + cellvalue + ","
Next
objWriter.WriteLine(rowLine)
rowLine = ""
Next
objWriter.Close()
objWriter = Nothing
MsgBox("Text written to file")
Catch e As Exception
MessageBox.Show("Error occured while writing to the file." + e.ToString())
Finally
FileClose(1)
End Try
Call copy_file()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'çall method SaveGridDataInFile
SaveGridDataInFile(Me.TextBox1.Text)
' FileCopy("H:\Data\2014\Software\VB2010\datagr_ex2.csv", "H:\Data\2014\Software\VB2010\datagr_ex.csv")
End Sub
Sub copy_file()
Dim FileToDelete As String
FileToDelete = "H:\Data\2014\Software\VB2010\datagr_ex.csv"
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
MsgBox("File Deleted")
End If
FileCopy("H:\Data\2014\Software\VB2010\datagr_ex2.csv", "H:\Data\2014\Software\VB2010\datagr_ex.csv")
End Sub
My guess is you need to close the StreamReader you use to load the file before you can reopen the file to save it. The StreamReader class implements IDisposable so you can use VB.Net's Using Statement to automatically close the file when you're finished reading, i.e.
If System.IO.File.Exists(fName) = True Then
Using objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
End Using
Else
MsgBox("File Does Not Exist")
End If

how to filter a datagridview when a database is not being used

I am able get the contents of a csv file to read into DataGridView1, but I am having trouble filtering the data from textbox2. I tried different things I have found online, but nothing has worked so far. this is what i have:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.Filter = "CSV Files (*.csv)|*.csv"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
Me.TextBox1.Text = fName
GetData(fName, DataGridView1, True)
End Sub
Private Sub GetData(ByVal Path As String, ByRef DG As DataGridView, Optional ByVal NoHeader As Boolean = False)
Dim Fields() As String
Dim Start As Integer = 1
If NoHeader Then Start = 0
If Not File.Exists(Path) Then
Return
End If
Dim Lines() As String = File.ReadAllLines(Path)
Lines(0) = Lines(0).Replace(Chr(34), "")
Fields = Lines(0).Split(",")
If NoHeader Then
For I = 1 To Fields.Count - 1
Fields(I) = Str(I)
Next
End If
For Each Header As String In Fields
DG.Columns.Add(Header, Header)
Next
For I = Start To Lines.Count - 1
Lines(I) = Lines(I).Replace(Chr(34), "")
Fields = Lines(I).Split(",")
DG.Rows.Add(Fields)
Next
End Sub
I just want to be able to filter say column 5 (no column headers in csv file) by typing something in textbox2. Any help would be greatly appreciated. Thank you
Don't add the values to a DGV, but instead use a DataTable then just make a query on that. Example considers you have a combobox for some filter choices - they are other ways to get this to depending on your needs. This method requires you to have headers though.
Private dt As New DataTable
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.Filter = "CSV Files (*.csv)|*.csv"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
Me.TextBox1.Text = fName
LoadData(fName)
FilterData(combobox1.Text, "some column name")
End Sub
Private Sub LoadData(ByVal Path As String)
Dim Fields() As String
Dim Start As Integer = 1
If NoHeader Then Start = 0
If Not File.Exists(Path) Then
Return
End If
Dim Lines() As String = File.ReadAllLines(Path)
Lines(0) = Lines(0).Replace(Chr(34), "")
Fields = Lines(0).Split(",")
For I = 1 To Fields.Count - 1
Fields(I) = Str(I)
Next
For Each Header As String In Fields
dt.Columns.Add(Header, Header)
Next
For I = Start To Lines.Count - 1
Lines(I) = Lines(I).Replace(Chr(34), "")
Fields = Lines(I).Split(",")
dt.Rows.Add(Fields)
Next
End Sub
Private Sub FilterData(filter As String, columnName as string)
Dim query = From dr As DataRow In dt.Rows Where dr(columnName).ToString = filter
DGV.DataSource = query
End Sub

Listview - select mosti similar item to value

How would one select item in listview (first column) that is most similar to string value from e.g. label or textbox.
Listview is populated with this code :
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListView1.Items.Clear()
ListView1.View = System.Windows.Forms.View.Details
ListView1.Columns.Add("COL1", 100, HorizontalAlignment.Left) 'KONTO
ListView1.Columns.Add("COL2", 140, HorizontalAlignment.Left) 'NAZIV
Dim FilePath As String = "W:\GLAVNI\KOR14\"
Dim DBF_File As String = "MATIKGL"
Dim ColName As String = "KONTO"
'Dim naz As String
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT * FROM MATIKGL ORDER BY KONTO, NAZIV", con)
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
While (reader.Read())
Me.ListView1.Items.Add(reader("KONTO"))
'ListView1.Items(i).SubItems.Add(rdr.Item("YourColumnName").ToString)
'BELOW SELECTS ALL ITEMS THAT STARTS WITH 2020-
For i = 0 To ListView1.Items.Count - 1
If ListView1.Items(i).ToString.Contains("2020-") Then
Else
ListView1.Items.Remove(ListView1.Items(i))
End If
Next
End While
Else
End If
End Using
End Using
con.Close()
End Using
End Sub
I have one textbox and a button.
Textual input from textbox should be compared with all items in listview and closest should be selected. One more thing : All items are sorted alphabetically
Button code is :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListView1.MultiSelect = False
ListView1.FullRowSelect = True
Dim checkInt As Integer = FindItem(ListView1, "2020-" & TextBox1.Text)'this one is changed since all items starts with "2020-"& UCASE TEXT
If checkInt <> -1 Then
ListView1.Items(checkInt).Selected = True
ListView1.Focus()
Else
Label1.Text = "Search string not found"
End If
End Sub
UPDATED CODE
Dim checkInt As Integer = FindItem(ListView1, "2020-" & TextBox3.Text)
If checkInt <> -1 Then
TextBox4.Focus()
Else
Label14.Text = "NEMA"
On Error GoTo ext
Dim li As ListViewItem
ListView1.SelectedItems.Clear()
ListView1.HideSelection = False
li = ListView1.FindItemWithText("2020-" & UCase(TextBox3.Text))
If Not (li Is Nothing) Then
Me.ListView1.Focus()
li.Selected = True
li.EnsureVisible()
ElseIf li Is Nothing Then
li = ListView1.FindItemWithText("2020-" & Strings.Left(TextBox3.Text, 1))
Me.ListView1.Focus()
li.Selected = True
li.EnsureVisible()
Else
End If
Exit Sub
ext:
TextBox3.Text = ""
TextBox3.Focus()
Label14.Text = "String not found"
End If
This one works.
I know it's not the best solution but it's working.
Could fixed this without your help, thank you Phillip Trelford
Define a function to score two strings for closeness then use LINQ to find the lowest score, i.,e.
' Example score function
Function Score(a As String, b As String) As Integer
Dim index = 0
While index < a.Length And index < b.Length
Dim diff = Math.Abs(AscW(a(index)) - AscW(b(index)))
If diff <> 0 Then Return diff
index += 1
End While
Return Math.Abs(a.Length - b.Length)
End Function
Function Closest(searchWord As String, words As String()) As String
Dim ordered =
From w In words
Select Word = w, Score = Score(w, searchWord)
Order By Score
Return ordered.First().Word
End Function
Sub Main()
Dim words = {"Alpha", "Apple", "Ask"}
Dim searchWord = "Ann"
Dim word = Closest(searchWord, words)
Console.WriteLine(word)
End Sub
Update
To select the value in a WinForms ListView, you need to do roughly this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListView1.MultiSelect = False
ListView1.FullRowSelect = True
Dim prefix = "2020-"
' Extract items from Listview
Dim items = New List(Of String)()
For Each item In ListView1.Items
items.Add(item)
Next
Dim words = items.ToArray()
Dim searchWord = TextBox1.Text
Dim resultWord = Closest(searchWord, words)
'this one is changed since all items starts with "2020-"& UCASE TEXT
Dim checkInt As Integer = FindItem(ListView1, prefix & resultWord)
If checkInt <> -1 Then
ListView1.Items(checkInt).Selected = True
ListView1.Focus()
Else
Label1.Text = "Search string not found"
End If
End Sub