writing to text file separated by | - vb.net

i am working on windows application.i am taking value from my sql database then writing to one .txt file.i have a code like this:
sql = "select * from " & strtablename
cmd = New SqlCeCommand(sql, CONN)
dr = cmd.ExecuteReader()
ListBox1.Items.Add("Extracting " & strfilename)
ListBox1.Refresh()
While (dr.Read())
sw = New StreamWriter(hht_Memory & "\Export\" & strfilename & ".txt", True)
prcount = 0
fvalues = ""
For I = 0 To dr.FieldCount - 1
If fvalues = "" Then
fvalues = IIf(IsDBNull(dr(I)), "", dr(I))
fvalues = Trim(Replace(fvalues, "'", ""))
Else
fvalues = fvalues & ", "
fvalues = fvalues & IIf(IsDBNull(dr(I)), "", dr(I))
fvalues = Trim(Replace(fvalues, "'", ""))
End If
Next I
sw.WriteLine(fvalues)
prcount = prcount + 1
sw.Close()
this is writing to text file.but each value separated by comma.i want to separate each value by |.
what the changes i have to make in my code?

This line:
fvalues = fvalues & ", "
should be changed to:
fvalues = fvalues & "| "

Related

Need Help for Updating database in vb.net

Someone knows why I got an exception when the code running at cmd.ExecuteNonQuery()? when I update Date, it runs perfectly but when I update the Finish date, I got that error.
This is the code
Call connection()
If txt_UpCom.Text = "" Or cbCom.SelectedItem = "" Then
If txt_ComNew.Enabled = True Then
MessageBox.Show("Please fill the entire data!")
End If
Else
Try
Dim str As String
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE complain SET " & cbCom.SelectedItem & "= '" & comdate & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE complain SET " & cbCom.SelectedItem & " = '" & txt_ComNew.Text & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
End If
cmd = New MySql.Data.MySqlClient.MySqlCommand(str, conn)
cmd.ExecuteNonQuery()
msgBoxSuccess.ShowDialog()
conn.Close()
Catch ex As Exception
MessageBox.Show("Unable to Update")
End Try
End If
This is the table in database
As #Jacek Wróbel mentioned in the comments, you should keep the column names between [] (square brackets) or "" (double quots). The same thing goes for table names (or any other SQL objects for that matter).
Long story short, change this part of your code:
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE complain SET " & cbCom.SelectedItem & "= '" & comdate & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE complain SET " & cbCom.SelectedItem & " = '" & txt_ComNew.Text & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
End If
to this:
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE `complain` SET `" & cbCom.SelectedItem & "` = '" & comdate & "' WHERE `ComplainID` = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE `complain` SET `" & cbCom.SelectedItem & "` = '" & txt_ComNew.Text & "' WHERE `ComplainID` = '" & txt_UpCom.Text & "'"
End If
Note: I prefer to keep things consistant, so I added [] to each object whether it contains spaces or not.

How to get default value of a row?

Actually i'm formatting data to insert in my MySQL DB and i'm at the point where i'm managing the NULL values.
So for manage it i've set a try catch inside the if where i look for datatype and now i have to put in the Catch exception the default value of certain type.
But how can i do it in VB.NET?
Here is my code, any suggestion for code improvment will be grateful
For Each row As DataRow In ds.Tables(0).Rows
righe = ""
For Each column As DataColumn In ds.Tables(0).Columns
If column.DataType = Type.GetType("System.DateTime") Then
Try
righe &= "'" & Format(row.Item(column.ColumnName), "yyyy-MM-dd") & "', "
Catch ex As Exception
End Try
ElseIf column.DataType = Type.GetType("System.TimeSpan") Then
righe &= "'" & Format(row.Item(column.ColumnName).ToString, "HH\:mm\:ss") & "', "
ElseIf column.DataType = Type.GetType("System.Int32") Then
righe &= row.Item(column.ColumnName) & ", "
ElseIf column.DataType = Type.GetType("System.Single") Then
righe &= Replace(row.Item(column.ColumnName), ",", ".") & ", "
ElseIf column.DataType = Type.GetType("System.Byte") Then
righe &= row.Item(column.ColumnName) & ", "
ElseIf column.DataType = Type.GetType("System.Double") Then
righe &= Replace(row.Item(column.ColumnName), ",", ".") & ", "
ElseIf column.DataType = Type.GetType("System.String") Then
righe &= "'" & APICI(row.Item(column.ColumnName)) & "', "
End If
Next
righe = Mid(righe, 1, Len(righe) - 2)
Next

ArgumentException when attempting to create image from stream

there's an error showing up after i update the data in my datagridview and after i click the row of updated data in my datagridview this error will shown up
Private Sub DataGridView2_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellClick
Dim i As Integer
i = DataGridView2.CurrentRow.Index
Me.txtEmployeeID.Text = DataGridView2.Item(0, i).Value
Me.txtFirstName.Text = DataGridView2.Item(1, i).Value
Me.txtMiddleName.Text = DataGridView2.Item(2, i).Value
Me.txtLastName.Text = DataGridView2.Item(3, i).Value
Me.txtGender.Text = DataGridView2.Item(4, i).Value
Me.txtContactNumber.Text = DataGridView2.Item(5, i).Value
Me.txtupAge.Text = DataGridView2.Item(6, i).Value
Me.txtupAddress.Text = DataGridView2.Item(7, i).Value
Me.Bdate.Text = DataGridView2.Item(8, i).Value
Me.txtPos.Text = DataGridView2.Item(9, i).Value
If DataGridView2.Item(10, i).Value Is Nothing Then Return
Using m As MemoryStream = New MemoryStream(CType(DataGridView2.Item(10, i).Value, Byte()))
PictureBox2.Image = CType(Image.FromStream(m).Clone(), Image)
End Using
End Sub
**EDIT**
when im updating, the image type in my database will change into 0x which is no image are saved.
this is the code of my update
cn.Close()
cn.Open()
With cmd
.Connection = cn
.CommandText = ("Update TBL_EMPLOYEE SET FirstName= '" & txtFirstName.Text & "', MiddleName='" & txtMiddleName.Text & "',LastName='" & txtLastName.Text & "', Gender='" & txtGender.Text & "',Age='" & txtupAge.Text & "' ,Address='" & txtupAddress.Text & "', Position='" & txtPos.Text & "',BirthDate='" & Bdate.Value.Date & "', [Picture]=#PID where [EmployeeID]=#EID ")
.Parameters.AddWithValue("#EID", CInt(txtEmployeeID.Text))
.Parameters.Add("PID", SqlDbType.Image).Value = ms.ToArray()
.ExecuteNonQuery()
.Dispose()
.Parameters.Clear()
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtGender.Text = ""
txtContactNumber.Text = ""
txtupAge.Text = ""
txtupAddress.Text = ""
txtPos.Text = ""
Bdate.Text = ""
PictureBox2.Image = Nothing
MsgBox("Employee Updated", vbInformation, "Information Message")
datagridshow()
End With
End If
when i update this image the image will not save. there's wrong syntax in my update
im missing this code : PictureBox2.Image.Save(ms, PictureBox2.Image.RawFormat) my bad. :'(
If you're sure DataGridView2.Item(10, i).Value has a value here then probably the MemoryStream is being Disposed too quickly. I'd suggest trying:
m As MemoryStream = New MemoryStream(CType(DataGridView2.Item(10, i).Value, Byte()))
PictureBox2.Image = Image.FromStream(m)
without Using

Select records from ms access table using query with two date conditions and another

I am using a select statement to retrieve records from an ms access table between two dates and another condition to check for customers name
I get the error "No value given for one or more required parameters"
The code is as below
Try
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
Dim dtDate1 As DateTime = DateTime.Parse(dtpDateFrom.Text)
Dim dtDate2 As DateTime = DateTime.Parse(dtpDateTo.Text)
''''SQL_PaymentsP = "SELECT InvoiceID,CustomerName,InvoiceDate,InvoiceAmount,PaymentDesc,PaidAmount,DatePaid,CurrentBalance FROM Payments WHERE [DatePaid] BETWEEN #" & dtDate1.ToString("MM/dd/yyyy") & "# AND #" & dtDate2.ToString("MM/dd/yyyy") & "# " & "OR [CustomerName] = " & txtCustomer.Text & ""
SQL_PaymentsP = "SELECT Payments.PaymentID, Payments.InvoiceID, Payments.CustomerName, Payments.InvoiceDate, Payments.InvoiceAmount, Payments.PaymentDesc, Payments.PaidAmount, Payments.DatePaid, Payments.CurrentBalance, Payments.Status FROM Payments WHERE Payments.DatePaid Between #" & dtDate1.ToString("MM/dd/yyyy") & "# And #" & dtDate2.ToString("MM/dd/yyyy") & "# " & " OR " & "Payments.CustomerName =" & txtCustomer.Text & ""
' SQLInvoicesP = "Select DateInvoice,IDInvoices,InvoiceAmount,CustomerName,Mode from Invoices where DateInvoice between #" & dtDate1.ToString("MM/dd/yyyy") & "# and #" & dtDate2.ToString("MM/dd/yyyy") & "#"
DataSet_PaymentsP.Clear()
Dim DataAdapter_PaymentsP As New OleDbDataAdapter(SQL_PaymentsP, Conn)
DataAdapter_PaymentsP.Fill(DataSet_PaymentsP, "Payments")
Conn.Close()
Application.DoEvents()
Dim ConInfo As New CrystalDecisions.Shared.TableLogOnInfo
ConInfo.ConnectionInfo.ServerName = Application.StartupPath & "\DB.mdb"
ConInfo.ConnectionInfo.DatabaseName = "kuku.mdb"
ConInfo.ConnectionInfo.UserID = "Admin"
ConInfo.ConnectionInfo.Password = ""
Dim rpt1 As New CrystalReport5
rpt1.Database.Tables(0).ApplyLogOnInfo(ConInfo)
rpt1.SetDataSource(DataSet_PaymentsP)
rpt1.SetParameterValue("Start_Date", dtDate1)
rpt1.SetParameterValue("End_Date", dtDate2)
rpt1.SetParameterValue("CustomerName", txtCustomer.Text)
rpt1.SetParameterValue("Author", FormMain.XN.Text)
Dim frm As New FormPrint
frm.CrystalReportViewer1.ReportSource = rpt1
frm.CrystalReportViewer1.LogOnInfo(0).ConnectionInfo.Password = "yazsys.com1234"
frm.ShowDialog()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
I just did add the single quotation marks as shown below and the select query can now retrieve records fro ms access
SQL_PaymentsP = "SELECT Payments.PaymentID, Payments.InvoiceID,
Payments.CustomerName, Payments.InvoiceDate, Payments.InvoiceAmount,
Payments.PaymentDesc, Payments.PaidAmount, Payments.DatePaid, Payments.CurrentBalance, Payments.Status FROM Payments WHERE Payments.DatePaid Between '#" & dtDate1.ToString("MM/dd/yyyy") & "#' And '#" & dtDate2.ToString("MM/dd/yyyy") & "#' OR " & "Payments.CustomerName ='" & txtCustomer.Text & "'"

Data gets stored in database from one tab page but it is not shown in another tab page in vb.net

I am using Visual Studio 2010 which has a form with a TabControl containing multiple tab pages.
1st tab page creates employee id and details about the employee which gets stored in the SQL server database successfully.2nd tab page has a ComboBox to display the employee id but it does not show the employee id which was created in the 1st tab page.When i close the project and run it again it displays the employee id.
How do i rectify this? Dim OpenDialog As New OpenFileDialog
With OpenDialog
.Filter = "Image Files (*.gif,*.jpg,*.jpeg,*.bmp,*.png)|*.gif;*.jpg;*.jpeg;*.bmp;*.png"
.Title = "Select A File"
End With
If gender.SelectedIndex = 0 Then
gend = "Male"
Else
gend = "Female"
End If
If eblood.SelectedIndex = 0 Then
blood = "A +ve"
ElseIf eblood.SelectedIndex = 1 Then
blood = "A -ve"
ElseIf eblood.SelectedIndex = 2 Then
blood = "B +ve"
ElseIf eblood.SelectedIndex = 3 Then
blood = "B -ve"
ElseIf eblood.SelectedIndex = 4 Then
blood = "AB +ve"
ElseIf eblood.SelectedIndex = 5 Then
blood = "AB -ve"
ElseIf eblood.SelectedIndex = 6 Then
blood = "O +ve"
Else
blood = "O -ve"
End If
If (String.IsNullOrWhiteSpace(eid.Text.Trim())) Or (String.IsNullOrWhiteSpace(fname.Text.Trim())) Or (String.IsNullOrWhiteSpace(lname.Text.Trim())) Or (String.IsNullOrWhiteSpace(gender.Text.Trim())) Or (String.IsNullOrWhiteSpace(gender.Text.Trim())) Or (String.IsNullOrWhiteSpace(country.Text.Trim())) Or (String.IsNullOrWhiteSpace(eaddress.Text.Trim())) Or (String.IsNullOrWhiteSpace(equali.Text.Trim())) Or (String.IsNullOrWhiteSpace(eblood.Text.Trim()) Or (String.IsNullOrWhiteSpace(TextBox_browse.Text.Trim()))) Then
MsgBox("Please Fill all the Fields", vbExclamation)
Else
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
myconnection = New SqlConnection("Data Source=localhost\sqlexpress;Initial Catalog=billing;Integrated Security=True")
Try
myconnection.Open()
mycommand = New SqlCommand("insert into b_emp_details([ed_id],[ed_first_name],[ed_last_name],[ed_dob],[ed_phone_number],[ed_gender],[ed_joining_date],[ed_country],[ed_address],[ed_qualification],[ed_blood_grp],[ed_image],[ed_created_by],[ed_created_date]) values ('" & eid.Text & "','" & fname.Text & "','" & lname.Text & "','" & dob.Text.ToString & "','" & ph.Text & "','" & gend & "','" & doj.Text.ToString & "','" & country.Text & "','" & eaddress.Text & "','" & equali.Text & "','" & blood & "','" & Trim(TextBox_browse.Text) & "','" & global_user & "','" & global_date & "')", myconnection)
mycommand.ExecuteNonQuery()
mycommand.CommandText = "UPDATE b_emp_details SET [ed_image] ='" & Trim(TextBox_browse.Text) & "' where [ed_id]='" & eid.Text & "'"
mycommand.Connection = myconnection
dr = mycommand.ExecuteReader
Dim newimage As New BitmapImage
newimage.BeginInit()
newimage.UriSource = (New Uri(OpenDialog.FileName, UriKind.RelativeOrAbsolute))
TextBox_browse.Text = OpenDialog.FileName
newimage.EndInit()
MessageBox.Show("Employee Successfully Created...")
eid.Text = ""
fname.Text = ""
lname.Text = ""
dob.Text = ""
ph.Text = ""
gender.Text = ""
doj.Text = ""
country.Text = ""
eaddress.Text = ""
equali.Text = ""
eblood.Text = ""
TextBox_browse.Text = ""
Call ResetBindings()
Catch ex As Exception
MsgBox("Error: " + ex.Message + "Invalid Data..Please Enter A Valid Data....")
'MsgBox("Invalid Data..Please Enter A Valid Data....")
myconnection.Close()
End Try
End If