Invalid cast exception was unhandled when saving gridview to a file - vb.net

okay I am totally stuck.
I have been getting some help off and on throughout this project and am anxious to get this problem solved so I can continue on with the rest of this project.
I have a gridview that is set to save to a file, and has the option to import into excel.
I keep getting an error of this:
Invalid cast exception was unhandled.
At least one element in the source array could not be cast down to the destination array type.
Can anyone tell me in layman easy to understand what this error is speaking of?
This is the code I am trying to use:
Dim fileName As String = ""
Dim dlgSave As New SaveFileDialog
dlgSave.Filter = "Text files (*.txt)|*.txt|CSV Files (*.csv)|*.csv"
dlgSave.AddExtension = True
dlgSave.DefaultExt = "txt"
If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
fileName = dlgSave.FileName
SaveToFile(fileName)
End If
End Sub
Private Sub SaveToFile(ByVal fileName As String)
If DataGridView1.RowCount > 0 AndAlso DataGridView1.Rows(0).Cells(0) IsNot Nothing Then
Dim stream As New System.IO.FileStream(fileName, IO.FileMode.Append, IO.FileAccess.Write)
Dim sw As New System.IO.StreamWriter(stream)
For Each row As DataGridViewRow In DataGridView1.Rows
Dim arrLine(9) As String
Dim line As String
**row.Cells.CopyTo(arrLine, 0)**
line = arrLine(0)
line &= ";" & arrLine(1)
line &= ";" & arrLine(2)
line &= ";" & arrLine(3)
line &= ";" & arrLine(4)
line &= ";" & arrLine(5)
line &= ";" & arrLine(6)
line &= ";" & arrLine(7)
line &= ";" & arrLine(8)
sw.WriteLine(line)
Next
sw.Flush()
sw.Close()
End If
I bolded the line where it shows in debug, and I really dont see what all the fuss is about LOL

If we assume you only want the value of the cell, then your method is incorrect, as it will try to copy the entire cell to the array.
Would this work for you?
//**row.Cells.CopyTo(arrLine, 0)**
line = row.Cells[0].Value.ToString()
line &= ";" & row.Cells[1].Value.ToString()
line &= ";" & row.Cells[2].Value.ToString()
line &= ";" & row.Cells[3].Value.ToString()
line &= ";" & row.Cells[4].Value.ToString()
line &= ";" & row.Cells[5].Value.ToString()
line &= ";" & row.Cells[6].Value.ToString()
line &= ";" & row.Cells[7].Value.ToString()
line &= ";" & row.Cells[8].Value.ToString()
sw.WriteLine(line)

I generally try to avoid VisualBasic (the syntax always seems opposite to me), but from a little bit of Googling at the VB docs, I'd hazard a guess that you have a type mismatch between your string array (arrLine) and what row.Cells is trying to copy into it.

Related

Adding a new line Richtextbox

Can anyone correct me on what is wrong with this code?
I can't add a new line inside Richtextbox control
Dim sb = New System.Text.StringBuilder()
sb.Append("{\rtf1\ansi")
sb.Append("\b " & TextBox2.Text & "\b0" & Environment.NewLine & "my body")
sb.Append("}")
Textbox.Rtf = sb.ToString
Because you aren't using rtf codes. Try:
sb.Append("\b " & TextBox2.Text & "\b0\par my body")

NON QUOTATION MARK IN CSV FILE BUT IN TXT FILE IT HAVE

Hi the below code was my code in creating csv file. The creation of csv is alright but when the csv convert to text file they sey it should have quotation mark between the beginning and in the end of the value. EX: in CSV File the value was: Jham, and in the textfile it should be : "Jham" - how can i manage it? can someone help?
listofValue = ZipFileStr & "," & Img1Val & "," & Img2Val & "," & RExVal & "," & BundleNo & "," & BundleNo & "," & URNVal & "," & PromocodeVal & "," & ZipFileStore & "," & SNumVal & "," & DpackVal & "," & ArrivalDate & "," & CompleteDateTwo & "," & KidPCVal & "," & MDBName
Dim PathX As String = TempPath & "\"
If Not IO.Directory.Exists(PathX) Then
MkDir(PathX)
End If
Dim sampleX As String = PathX & ZipFileStr & "P.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(sampleX, True)
outFile.WriteLine(listofValue)
outFile.Close()
Firstly, when posting code snippets, please format them for readability. I have fixed that for you.
Secondly, there's no such thing as "converting" between a CSV file and a text file. A CSV is just plain text. If the text contains record and field delimiters then it is a CSV file, otherwise it's not. It's plain text either way.
As for the question, I would suggest writing a CSV with quoted values something like this:
Dim line = String.Format("""{0}"",""{1}"",""{2}""",
firstValue,
secondValue,
thirdValue)
The use of String.Format or, in VB 2015, string interpolation makes the code far more readable. As for putting a double-quote in a literal string, you simply escape it with another double-quote. You might also use the ControlChars.Quote field:
Dim line = String.Format("{0}{1}{0},{0}{2}{0},{0}{3}{0}",
ControlChars.Quote,
firstValue,
secondValue,
thirdValue)
Note that it is generally only text values that get quoted, not numbers and dates and the like. That's because the main reason for the quoting is to allow a value to contain delimiters, i.e. commas or line breaks. If none of your values do contain delimiters then you can safely omit the quotes altogether.
EDIT: As an example, here's how I might write a DataTable to a CSV file where the first and fourth columns contain String values, the second column contains numbers and the third column contains Date values.
Private Sub WriteToCsv(table As DataTable, path As String)
Dim lines As New List(Of String)
For Each row As DataRow In table.Rows
lines.Add(String.Format("""{0}"",{1},{2:yyyy-MM-dd},""{3}""",
row(0),
row(1),
row(2),
row(3)))
Next
IO.File.WriteAllLines(path, lines)
End Sub

VB.NET Database Retrieval

I have a VB.NET application that has instant messaging-like functionality with a database. It can retrieve the values just fine, but the problem is the formatting isnt coming out right. I want the format to be as follows:
Sender: Message
(so...)
David: Hey guys
What I've tried below doesn't get me the result I'm looking for, it just prints the sender at the top of the rich textbox in my application and the message at the bottom, does anyone have any ideas?
'-------------------Retreives the message-------------------------------------------------------------
Dim sqlStr As String = "SELECT * FROM dojodb.chats"
Dim chatcommand As New MySqlCommand(sqlStr, MysqlConn)
Dim rdr As MySqlDataReader = chatcommand.ExecuteReader()
Dim tbl As New DataTable
tbl.Load(rdr)
'-------For every row, print the message, skip a line, and add 1 so it goes to next msg-- ------
For i As Integer = 0 To tbl.Rows.Count - 1
rowIndex = i
strSender &= CStr(tbl.Rows(rowIndex)("Sender")) & vbNewLine
strMessage &= CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
strOutPut = strSender + ": " + strMessage
Next
txtGroupChat.Text = strOutPut
'Keeps the richtextbox scrolled to the bottom so that most recent msg is always shown
txtGroupChat.SelectionStart = txtGroupChat.Text.Length
txtGroupChat.ScrollToCaret()
strOutPut = "" 'clearing the string so that it does not print out duplicate info next time
strSender = ""
strMessage = ""
'-------------------------End Retrive---------------------------------------
I feel a bit embarrassed posting this, but...
strSender = CStr(tbl.Rows(rowIndex)("Sender")) & ": "
strMessage = CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
strOutPut &= strSender & strMessage
What do you think vbNewLine does? Also, be careful of &=

How to read an excel while in use by another user with Oledb?

I have an excel on a shared drive and my application is using an Oledb connection to read data from the excel into a DataGridView.
cn = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;" + "data source=" + skuPath + ";Extended Properties=""Excel 12.0;HDR=YES;""")
q1 = "select * from [" + year + "$B4:AM300]"
da = New System.Data.OleDb.OleDbDataAdapter(q1, cn)
Try
cn.Open()
da.Fill(ds, "Table1")
Catch e As OleDb.OleDbException
Dim errorMsg As String
Dim i As Integer
errorMsg = ""
For i = 0 To e.Errors.Count - 1
errorMsg += "Index #" & i.ToString() & ControlChars.Cr _
& "Message: " & e.Errors(i).Message & ControlChars.Cr _
& "NativeError: " & e.Errors(i).NativeError & ControlChars.Cr _
& "Source: " & e.Errors(i).Source & ControlChars.Cr _
& "SQLState: " & e.Errors(i).SQLState & ControlChars.Cr
Next i
End Try
cn.Close()
dt = ds.Tables(0)
When the excel file is already open by another user you get this notification in excel:
And in those situations my code returns this error on the last line:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Additional information: Cannot find table 0.
So i understand is that because the file is in use then the entire connection returns nothing and data table is therefore empty.
I found a few way of determining if a file is in use or not but nothing regarding how to read from a file in use.
Is it possible? and if so how?
Please remember i only need to read the file and if its possible to always open it as a readonly that would awesome!
You can't. You have to close the open file before read it even if you use the ODBC(read only).
Ref: http://forums.asp.net/t/1083489.aspx?open+a+Microsoft+Jet+OLEDB+4+0+connection+to+excel+file+read+only

Arguments from Visual Basic to Batch File

I know this is easy. I am an administrator, not a FT programmer. I am trying to pass the prjFilename and emailFilename arguments to a Batch file. To ensure the values are correct, I am popping a MsgBox in the Else branch. Everything is fine there. The problem is that when I attempt to use the variable in the Batch file, that variable string is cut off at the very first space in the filename path.
So when I echo %1% to test it, I get a truncated path. Any help is appreciated.
If prjFilename = "" Then
MsgBox("Please select a GSA Project File to process")
ElseIf emailFilename = "" Then
MsgBox("Please select a list of emails to process")
Else
Dim DosRun As Process = New Process
Dim strArgs As String
MsgBox(prjFilename)
MsgBox(emailFilename)
strArgs = prjFilename & " " & emailFilename
MsgBox(strArgs)
DosRun.StartInfo.WindowStyle = ProcessWindowStyle.Maximized
DosRun.StartInfo.FileName = "C:\Users\Eric\Desktop\KRUSH\krush.cmd"
DosRun.StartInfo.Arguments = prjFilename & " " & emailFilename
DosRun.Start()
If either of prjFilename or emailFilename contain spaces, then you need to place double quotation characters around them when passing them to the batch file. A double quotation character literal in VBA is """" (I kid you not).
strArgs = """" & prjFilename & """" & " " & """" & emailFilename & """"
I normally define Public Const vbQuote as String = """" at the top of a module and use that.