Displaying a Image previous scanned or retrieved in Picturebox - mysql

I just want some help for my project which is RFID attendance system. The RFID tag should be scan to retrieve the information and Image from the database mysql. The first student will scan his RFID tag to display his picture in picturebox1 and when another student scan the picturebox1 will be updated to a new student picture and data and the previous one is on the picturebox2 displayed The issue here is how can I display the previous Image of the student. Just only the Image ,the data is not included.
I have a 2 picturebox
Picturebox1 is for new student scanned
Picturebox2 is for the previous one or the student who scan before the new.
Thank you guys ..Any suggestions and comment will totally appreciated
Here is my code
Private Sub studtag_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles studtag.TextChanged
If studtag.TextLength = 8 Then
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Dim query As String
query = "select * from dat.students"
cmd = New MySqlCommand(query, con)
Dim table As New DataTable
Try
con.Open()
'Gets or sets an SQL statement or stored procedure used to select records in the database.
With cmd
.Connection = con
.CommandText = "SELECT * from students where `studtags`='" & studtag.Text & "';"
End With
da.SelectCommand = cmd
da.Fill(table)
'it gets the data from specific column and fill it into textbox
studtag.Text = table.Rows(0).Item(0)
idno.Text = table.Rows(0).Item(1)
lastxt.Text = table.Rows(0).Item(2)
firstxt.Text = table.Rows(0).Item(3)
middletxt.Text = table.Rows(0).Item(4)
dob.Text = table.Rows(0).Item(6)
crsetxt.Text = table.Rows(0).Item(10)
tagtxt.Text = studtag.Text
timein.Text = times.Text
dr = cmd.ExecuteReader()
dr.Read()
If dob.Text = datenow.Text Then
greet.Text = "Happy Birthday To You"
End If
Dim img() As Byte = CType(dr("studpic"), Byte())
Using ms As New IO.MemoryStream(img)
PictureBox1.Image = Image.FromStream(ms)
End Using
insert()
loadtable()
Catch ex As Exception
Notenrolled.Show()
Finally
con.Dispose()
con.Close()
End Try
End If
End Sub
Public Sub loadtable()
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Dim SDA As New MySqlDataAdapter
Dim dbDataset As New DataTable
Dim bSource As New BindingSource
Try
con.Open()
Dim query3 As String
query3 = "select studtags,idno,lastxt,firstxt,middletxt,dob,log,timein,crse from dat.studlogs"
cmd = New MySqlCommand(query3, con)
SDA.SelectCommand = cmd
SDA.Fill(dbDataset)
bSource.DataSource = dbDataset
DataGridView1.DataSource = bSource
SDA.Update(dbDataset)
DataGridView1.Sort(DataGridView1.Columns(8), System.ComponentModel.ListSortDirection.Ascending)
If dbDataset.Rows.Count > 0 Then
logins.Text = table2.Rows.Count.ToString()
End If
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Private Sub Students_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
loadtable()
''Date Now
Timer2.Start()
Try
DataGridView1.AllowUserToAddRows = False ' Disabled or hide (*) Symbol...
DataGridView1.RowHeadersVisible = False 'To hide Left indicator..
DataGridView1.DefaultCellStyle.SelectionBackColor = Color.SteelBlue 'Selection backcolor....
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGoldenrodYellow 'Alternating Backcolor.
DataGridView1.AllowUserToResizeRows = False 'Disabled row resize...
DataGridView1.ReadOnly = True
DataGridView1.MultiSelect = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
DataGridView1.ShowRowErrors = False
DataGridView1.ShowCellErrors = False
table2.Columns.Add("Student Tag", Type.GetType("System.String"))
table2.Columns.Add("Student ID", Type.GetType("System.Int32"))
table2.Columns.Add("Last Name", Type.GetType("System.String"))
table2.Columns.Add("First Name", Type.GetType("System.String"))
table2.Columns.Add("Middle Name", Type.GetType("System.String"))
table2.Columns.Add("Status", Type.GetType("System.String"))
table2.Columns.Add("Birthday", Type.GetType("System.String"))
table2.Columns.Add("Time in", Type.GetType("System.String"))
table2.Columns.Add("Course/Sec", Type.GetType("System.String"))
Catch ex As Exception
End Try

It's quiet easy,You can use a button to display the previous image :
If datagridview1.CurrentRow.Index < datagridview1.Rows.Count Then
datagridview1.Rows(datagridview1.SelectedRows(0).Index - 1).Selected
= True
Dim pic As Byte()
pic = datagridview1.CurrentRow.Cells(1).Value
Dim ms As New MemoryStream(pic)
pbox1.BackgroundImage = Image.FromStream(ms)

Related

There is already an open Data Reader associated with this connection which must be closed first vb.net.vb

Dim Conn As MySqlConnection
Dim Command As MySqlCommand
Dim Reader As MySqlDataReader
Dim server As String = "serverxxxxxxxx.1;user=root;database=xxxxxxxxx"
Public Sub testing()
Conn = New MySqlConnection
Conn.ConnectionString = server
Dim datecompare As String = Date.Today.ToString("yyyy-MM-dd hh:mm:ss")
Dim primarykey1 As String = ""
Dim primarykey2 As String = ""
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim Query1 As String
Query1 = "Select * From `tblborrow` Where `DueDate` = '" & datecompare & "'"
Command = New MySqlCommand(Query1, Conn)
Reader = Command.ExecuteReader
While Reader.Read
primarykey1 = Reader.GetInt32("BorrowID")
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim query2 As String
query2 = "Update `tblborrow` Set `Remarks` = '" & "Due Date" & "' Where `BorrowID` = '" & primarykey1 & "'"
Command = New MySqlCommand(query2, Conn)
Reader = Command.ExecuteReader
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'end of duedate
End While
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'for OVER DUE
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim Query1 As String
Query1 = "Select * From `tblborrow` Where `DueDate` < '" & datecompare & "'"
Command = New MySqlCommand(Query1, Conn)
Reader = Command.ExecuteReader
While Reader.Read
primarykey2 = Reader.GetInt32("BorrowID")
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim query2 As String
query2 = "Update `tblborrow` Set `Remarks` = '" & "Over Due" & "' Where `BorrowID` = '" & primarykey2 & "'"
Command = New MySqlCommand(query2, Conn)
Reader = Command.ExecuteReader
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'end of Over Due
End While
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call testing()
End Sub
I created a public sub that will select and update the Remarks in my database based on the borrowID(this is auto increment). The save date in DueDate and compare i declare with the current time today, but every time i click the button where i saved the code i get this error There is already an openDataReaderassociated with this connection which must be closed first
i double checked my code and didn't miss to put reader.close() after every conn.close() or i don't know maybe i missed..
i tried some several changes in my code but still i get the same error.
can some help me and build my code? .. thanks.
Try to use different variable for the readers, maybe Reader1 and Reader2.
It's probably because you used the same reader to execute different query hence the already open datareader error.
You try to open the same book which is already open. At least make it a different book.
You are attempting to open 2 readers on a single connection. See the double headed arrows.
Reader = Command.ExecuteReader'<<----
While Reader.Read
primarykey1 = Reader.GetInt32("BorrowID")
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim query2 As String
query2 = "Update `tblborrow` Set `Remarks` = '" & "Due Date" & "' Where `BorrowID` = '" & primarykey1 & "'"
Command = New MySqlCommand(query2, Conn)
Reader = Command.ExecuteReader '<<----
If you break your code into logical units with only a single thing happening in each method it is a bit easier to see where things go wrong.
Keeping your database objects local to the methods where they are used allows you to be sure they are closed and disposed. Using...End Using blocks handle this for you even if there is an error.
Notice, in the 2 Update methods, the parameters are added outside the For loop and only the value that changes is set inside the loop.
Dim ConString As String = "serverxxxxxxxx.1;user=root;database=xxxxxxxxx"
Public Sub GetPKs()
Dim pkList As New List(Of Integer)
Dim DueDate As String = Date.Today.ToString("yyyy-MM-dd hh:mm:ss")
Using Conn As New MySqlConnection(ConString),
cmd As New MySqlCommand("Select BorrowID From tblborrow Where DueDate = #DueDate")
cmd.Parameters.Add("#DueDate", MySqlDbType.VarChar, 100).Value = DueDate
Conn.Open()
Using reader As MySqlDataReader = cmd.ExecuteReader
While reader.Read
pkList.Add(reader.GetInt32("BorrowID"))
End While
End Using
End Using
UpdateRemarks(pkList, DueDate)
End Sub
Private Sub UpdateRemarks(pks As List(Of Integer), DueDate As String)
Using con As New MySqlConnection(ConString),
cmd As New MySqlCommand("Update tblborrow Set Remarks = #DueDate Where BorrowID = #PK", con)
With cmd.Parameters
.Add("#DueDate", MySqlDbType.VarChar, 100).Value = DueDate
.Add("#PK", MySqlDbType.Int32)
End With
con.Open()
For Each i In pks
cmd.Parameters("#PK").Value = i
cmd.ExecuteNonQuery()
Next
End Using
End Sub
Private Sub GetOverduePKs()
Dim pkList As New List(Of Integer)
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("Select BorrowID From tblborrow Where DueDate < #DueDate")
cmd.Parameters.Add("#DueDate", MySqlDbType.VarChar, 100).Value = Date.Today.ToString("yyyy-MM-dd hh:mm:ss")
cn.Open()
Using reader = cmd.ExecuteReader
While reader.Read
pkList.Add(reader.GetInt32("BorrowID"))
End While
End Using
End Using
UpdateOverdueRemarks(pkList)
End Sub
Private Sub UpdateOverdueRemarks(pks As List(Of Integer))
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("Update tblborrow Set Remarks = 'Over Due' Where BorrowID = #PK")
cmd.Parameters.Add("#PK", MySqlDbType.Int32)
cn.Open()
For Each i In pks
cmd.Parameters("#PK").Value = i
cmd.ExecuteNonQuery()
Next
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
GetPKs()
GetOverduePKs()
End Sub
use 2 connections CONN and CONN2, with the same parameters, use CONN to open the QUERY1 reader. While reading, use CONN2 to create the 2nd query. Note that this works for MySQL. MS-Access can handle multiple commands in one connection, MySql cannot and needs separate connections. Sqlite cannot handle 2 simultanuos connections. there you have to use in incore temporary array or list. From a working program:
Dim DbConn As New MySqlConnection(SqlProv)
Dim DbConn2 As New MySqlConnection(SqlProv)
-
Dim SQLsfSelect As String = "SELECT CollSeq FROM ToBeIndexed WHERE CollCode = #CollCode"
Dim DRsfSelect As MySqlDataReader = Nothing
Dim DCsfSelect As MySqlCommand
Dim sfSelP1 As New MySqlParameter("#CollCode", MySqlDbType.VarChar, 4)
DCsfSelect = New MySqlCommand(SQLsfSelect, DbConn)
-
Dim SQLasSelect As String = "SELECT DISTINCT CollSeq FROM Data WHERE CollCode = #CollCode ORDER BY CollSeq"
Dim DRasSelect As MySqlDataReader = Nothing
Dim DCasSelect As MySqlCommand
Dim asSelP1 As New MySqlParameter("#CollCode", MySqlDbType.VarChar, 4)
DCasSelect = New MySqlCommand(SQLasSelect, DbConn2)
-
DbConn.Open()
sfSelP1.Value = CurCollCode
CollSeqToIdxC.Clear()
Try
DRsfSelect = DCsfSelect.ExecuteReader()
Do While (DRsfSelect.Read())
CollSeq = GetDbIntegerValue(DRsfSelect, 0)
DbConn2.Open()
asSelP1.Value = CurCollCode
Try
DRasSelect = DCasSelect.ExecuteReader()
Do While (DRasSelect.Read())
CollSeq = GetDbIntegerValue(DRasSelect, 0)
CollSeqToIdxC.Add(CollSeq, CStr(CollSeq))
Loop
Catch ex As Exception
MsgBox(ex.ToString(), , SysMsg1p(402, CurCollCode))
Finally
If Not (DRasSelect Is Nothing) Then
DRasSelect.Close()
End If
End Try
DbConn2.Close()
Loop
Catch ex As Exception
MsgBox(ex.ToString(), , SysMsg1p(403, CurCollCode))
Finally
If Not (DRsfSelect Is Nothing) Then
DRsfSelect.Close()
End If
End Try
DbConn.Close()

VB.NET MySQL query returns no value

I am trying to display value in combobox using MySQL in vb.net. Right now the problem that I am facing is that combobox is not displaying values from MySQL. I have the below code:
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "DB Connection Successful"
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label10.Text = READER.GetDouble("Price")
End While
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
However, using the above code Combobox1.Text returns nothing but if I use below code which has a different query it works:
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "DB Connection Successful"
Dim Query As String
Query = "select * from s974_db.processors"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sName = READER.GetString("Name")
ComboBox1.Items.Add(sName)
End While
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
Could someone please check and let me know what could be the issue? Thanks!
so the highlights as i mentioned them in the comments
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' You need only to open aconnection once
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "db connection successful"
'First load both Combobox
Dim query As String
query = "select * from s974_db.processors"
COMMAND = New MySqlCommand(query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sname = READER.GetString("name")
ComboBox1.Items.Add(sname)
ComboBox2.Items.Add(sname)
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Closing
Try
MySqlConn.Close()
MySqlConn.Dispose()
Catch ex As Exception
End Try
End Sub
ANd now the Comboboxes
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
'Only when there is a item selected , ask for data
If ComboBox1.SelectedIndex > -1 Then
Try
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label11.Text = READER.GetDouble("Price")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End If
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
If ComboBox2.SelectedIndex > -1 Then
Try
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label10.Text = READER.GetDouble("Price")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End If
End Sub
This is exactly as i described on Form_load you fill both comboboxes
When you now change one of the comboxes one of the label change too.
Sometimes you have to update the Element to see a change
in that case you write at the end of the loop
Label10.Update()
Starting at the top...
Keep your database objects local to the method where they are used. (Not Form level variables) You can make the connection string a class level string variable. This is the only way you can ensure that they are closed and disposed.
Using...End Using blocks will close and dispose your database objects even if there is an error. The constructor of the connection takes the connection string. Connections are precious objects. Don't open the connection until directly before the .Execute method and close it as soon as possible.
It doesn't make much sense that the user could select an item from ComboBox1 before the Form.Load.
In general, we don't want to download anymore data than necessary and we want to hit the database as little as possible. In the Form.Load we bind the combobox to a data table that contains the name and price fields, setting the display and value members. Now, whenever the user picks a name in the combo we can retrieve the price without connecting to the database again.
I noticed that you were using Val in another event. This is an old VB6 method that can give you unexpected results. .Net and vb.net have all sorts of ways to get numbers out of strings that are faster and more reliable. CInt, .TryParse, .Parse, CType, Convert.To etc.
Public Class Form1
Private ConString As String = "server=localhost;userid=root;password=root;database=s974_db"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Fill combobox
Dim dt As New DataTable
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("select Name, Price from processors;", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using 'Closes and disposes both connection and command
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "Price"
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
Label10.Text = ComboBox1.SelectedValue.ToString
ClearLabels()
End Sub
Private Sub ClearLabels()
Label11.Text = ""
Label12.Text = ""
Label13.Text = ""
Label14.Text = ""
Label15.Text = ""
Label16.Text = ""
Label17.Text = ""
Label18.Text = ""
Label19.Text = ""
Label20.Text = ""
End Sub
End Class

Picture from mysql to PictureBox

I'm trying to show image from mysql to PictureBox, and I set it to show on a form load. But when my form loads, picture doesn't appear, and the code shows no errors. Here's the code:
Private Sub frmStudentskiPanel_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Konekcija = New MySqlConnection
Konekcija.ConnectionString = "server=localhost; userid=root; password=masterzlaja123; database=proba"
Dim Command As MySqlCommand
Dim reader As MySqlDataReader
Dim img() As Byte
Try
Konekcija.Open()
Dim Query As String
Query = "Select Slika from proba.studenti where Korisnicko_ime = '" & Label2.Text & "' "
Command = New MySqlCommand(Query, Konekcija)
reader = Command.ExecuteReader
While reader.Read()
img = reader.Item("Slika")
Dim mstream As New MemoryStream(img)
PictureBox1.Image = Image.FromStream(mstream)
End While
Konekcija.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Konekcija.Dispose()
End Try
End Sub
End Class

how to display selected value in mysql database in label through vb.net

i have a code but it's not working. i was trying to put a value in label2 but it's not working. please help me.
Private Sub student_no_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles student_no.Click
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server = localhost; port=3307; user id = root; password = 1234; database = sample;"
Dim READER As MySqlDataReader
Try
MySqlConnection.Open()
Dim query As String
query = " select id from sample.student where last_name = '" & txtlastname.Text & "' "
Dim Command As New MySqlCommand(query, MySqlConnection)
READER = Command.ExecuteReader
Label2.Text = query.ToString
MessageBox.Show("Student Number Generated")
MySqlConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MySqlConnection.Dispose()
End Try
End Sub
You are using .ToString on query, which is a string. What you should be doing is operations on the READER object.
Since SELECT will always return a list of results, you have to treat the results as such, like...
While READER.Read()
MessageBox.Show((READER.GetInt32(0)))
End While
.Read() returns the next element in the returned rowset
If READER.Read() Then
Label2.Text = READER.GetString(0)
End If

from DataGridView saving to text file issue when saving date values on vb.net

I have a problem. Whenever I save data into a text file from a DataGridView, the format of the date gets automatically converted to date along with time. It shouldn't be like that because the data from where the datagridview is basing from is only pure date but when I transfer it into a text file it automatically adds a time. It looks something like this:
246,4/20/2013 12:00:00 AM,01:00:00,p
How do I remove the time (12:00:00 AM) that comes along with the date?
These are codes for the datagrid:
Private Sub load_table()
sConnection = New MySqlConnection
sConnection.ConnectionString = "server=localhost;userid=root;password=;database=cph;Convert Zero Datetime=True"
Dim SDA As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim bSource As New BindingSource
Try
sConnection.Open()
Dim Query As String
Query = "select * from swipe_table"
sqlCommand = New MySqlCommand(Query, sConnection)
SDA.SelectCommand = sqlCommand
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView1.DataSource = bSource
SDA.Update(dbDataSet)
sConnection.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
sConnection.Dispose()
End Try
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
sConnection = New MySqlConnection
sConnection.ConnectionString = "server=localhost;userid=root;password=;database=cph;Convert Zero Datetime=True"
Dim SDA As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim bSource As New BindingSource
Try
sConnection.Open()
Dim Query As String
Query = "select * from swipe_table"
sqlCommand = New MySqlCommand(Query, sConnection)
SDA.SelectCommand = sqlCommand
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView1.DataSource = bSource
SDA.Update(dbDataSet)
sConnection.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
sConnection.Dispose()
End Try
End Sub
And these codes are for the saving to text file part:
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim filename As String = String.Empty
Dim sfd1 As New SaveFileDialog()
sfd1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
sfd1.FilterIndex = 2
sfd1.RestoreDirectory = True
sfd1.Title = "Save Text File"
If sfd1.ShowDialog() = DialogResult.OK Then
If sfd1.FileName = String.Empty Then
MsgBox("Please input filename")
Else
filename = sfd1.FileName.ToString
Saveto_TextFile(DataGridView1, filename)
End If
End If
End Sub
Sub Saveto_TextFile(ByVal dvList As DataGridView, ByVal filename As String)
Dim strDestinationFile As String = "" & filename & ".txt"
Dim tw As TextWriter = New StreamWriter(strDestinationFile)
Dim LineToWrite As String = String.Empty
Try
For _Row As Integer = 0 To DataGridView1.Rows.Count - 1
LineToWrite = String.Empty
For _Column As Integer = 0 To DataGridView1.Columns.Count - 1
If DataGridView1.Rows(_Row).Cells(_Column).Value IsNot Nothing Then
LineToWrite &= "," & DataGridView1.Rows(_Row).Cells(_Column).Value.ToString
Else
LineToWrite &= ","
End If
Next
LineToWrite = LineToWrite.Remove(0, 1) 'remove the first comma
tw.WriteLine(LineToWrite)
Next
tw.Flush()
tw.Close()
MessageBox.Show("Data Saved Successfully")
Catch ex As Exception
MessageBox.Show("An error occurred")
End Try
End Sub
Check the type of the cell value...
For _Column As Integer = 0 To DataGridView1.Columns.Count - 1
If DataGridView1.Rows(_Row).Cells(_Column).Value IsNot Nothing Then
If DataGridView1.Rows(_Row).Cells(_Column).Value.GetType Is GetType(Date) AndAlso CDate(DataGridView1.Rows(_Row).Cells(_Column).Value).TimeOfDay = New Date().TimeOfDay Then
LineToWrite &= "," & CDate(DataGridView1.Rows(_Row).Cells(_Column).Value).ToShortDateString
Else
LineToWrite &= "," & DataGridView1.Rows(_Row).Cells(_Column).Value.ToString
End If
Else
LineToWrite &= ","
End If
Next
There's no such thing as a "pure date". The .NET DateTime type always represents a date and a time. It's accepted that you can zero the time to represent just a date but the time portion is till there and you'll see it when you output the value using ToString with no parameters. You should either call ToShortDateString or else call ToString and pass an appropriate format specifier, e.g. "d" for short system date format or "M/dd/yyyy" for US date format.