vb.net check if function don't return anything - vb.net

I have a vb.net function is which I am doing some thing which is returning a gridview to send it in email.Problem is that when I call the function in email then email is sent even there is nothing returned by function. I don't to send blank email at all. I want to when function return nothing then it shouldn't send email. Here is My function
Public Function emaildata(ByVal grdv As GridView, ByVal chk As String, ByVal celpos As Integer) As GridView
Dim comm As OleDbCommand = New OleDbCommand()
Dim bpv As String = ""
Dim gv As New GridView
For Each gvrow As GridViewRow In grdv.Rows
Try
Dim rdobtn As RadioButtonList = CType(gvrow.FindControl(chk), RadioButtonList)
If rdobtn.SelectedValue.Equals("5") Or rdobtn.SelectedValue.Equals("1") Or rdobtn.SelectedValue.Equals("6") Or rdobtn.SelectedValue.Equals("4") Or rdobtn.SelectedValue.Equals("2") Then
If bpv <> "" Then
bpv += ","
End If
bpv += gvrow.Cells(celpos).Text
comm.CommandText = "SELECT row_number() over(order by rownum) Sr, to_char(chq_num) Cheque#,to_char(bpv_amt,'9,999,999,999') Amount,vch_nar Narration,bnf_nam PartyName,acc_des Bank from CHECK_DATA where bpv_num in(" & bpv.ToString() & ") and BPV_DTE=to_date('" & TreeView2.SelectedValue & "') union all SELECT null,'Total :',to_char(sum(bpv_amt),'9,999,999,999') Amount,null,null,null from CHECK_DATA where bpv_num in(" & bpv.ToString() & ") and BPV_DTE=to_date('" & TreeView2.SelectedValue & "')"
comm.CommandType = CommandType.Text
comm.Connection = con
Dim da As New OleDbDataAdapter(comm)
Dim ds As New DataSet
da.Fill(ds)
gv.DataSource = ds
gv.DataBind()
End If
Catch ex As Exception
Response.Write("There is Problem In Cheque Approval System Please Contact With IT")
End Try
Next
Return gv
End Function
And I Call this in email function as a subject like this
email("malik.adeel#shakarganj.com.pk", "[Cheque Approval] GM Finance Reviewed (" & TreeView2.SelectedValue & ")" & subsmcnt(GridView5, "chkStatusGM", 4), gridhtm(emaildata(GridView5, "chkStatusGM", 4)))
How can I do this that if emaildata(GridView5, "chkStatusGM", 4) returning nothing email shouldn't be sent?

Probably the easiest is to check if the GridView contains GridViewRows with the Count property:
Dim grdEmail = emaildata(GridView5, "chkStatusGM", 4)
If grdEmail.Rows.Count > 0
email("malik.adeel#shakarganj.com.pk",
"[Cheque Approval] GM Finance Reviewed (" & TreeView2.SelectedValue & ")" & subsmcnt(GridView5, "chkStatusGM", 4),
gridhtm(grdEmail))
End If

Related

if record exists update else insert sql vb.net

I have the following problem, I am developing a Clinic application using vb.net, the doctor has the ability to add medical information using checkboxes checkbox2.text = "Allergy" textbox15.text is the notes for Allergy, I want to insert the record if the patient's FileNo(Textbox2.text) doesn't exist, if it does then update the notes only, so far I was able to update it after 3 button clicks I don't know why????
any help is appreciated :)
thanks in advance
Dim connection3 As New SqlClient.SqlConnection
Dim command3 As New SqlClient.SqlCommand
Dim adaptor3 As New SqlClient.SqlDataAdapter
Dim dataset3 As New DataSet
connection3.ConnectionString = ("Data Source=(LocalDB)\v11.0;AttachDbFilename=" + My.Settings.strTextbox + ";Integrated Security=True;Connect Timeout=30")
command3.CommandText = "SELECT ID,Type FROM Medical WHERE FileNo='" & TextBox2.Text & "';"
connection3.Open()
command3.Connection = connection3
adaptor3.SelectCommand = command3
adaptor3.Fill(dataset3, "0")
Dim count9 As Integer = dataset3.Tables(0).Rows.Count - 1
If count9 > 0 Then
For countz = 0 To count9
Dim A2 As String = dataset3.Tables("0").Rows(countz).Item("Type").ToString
Dim B2 As Integer = dataset3.Tables("0").Rows(countz).Item("ID")
TextBox3.Text = A2
If A2 = CheckBox1.Text Then
Dim sql4 As String = "update Medical set MNotes=N'" & TextBox22.Text & "' where FileNo='" & TextBox2.Text & "' and Type = '" & CheckBox1.Text & "' and ID='" & B2 & "';"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
ElseIf A2 = CheckBox2.Text Then
Dim sql4 As String = "update Medical set MNotes=N'" & TextBox15.Text & "' where FileNo='" & TextBox2.Text & "' and Type = '" & CheckBox2.Text & "' and ID='" & B2 & "';"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Next
Else
If CheckBox1.Checked = True Then
Dim sql4 As String = "insert into Medical values('" & CheckBox1.Text & "',N'" & TextBox22.Text & "','" & TextBox2.Text & "')"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
If CheckBox2.Checked = True Then
Dim sql4 As String = "insert into Medical values('" & CheckBox2.Text & "',N'" & TextBox15.Text & "','" & TextBox2.Text & "')"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End If
I think one of your problems may be related to your reducing the count of your table rows by 1 and then testing it above 0:
Dim count9 As Integer = dataset3.Tables(0).Rows.Count - 1
If count9 > 0 Then
Try changing to:
Dim count9 As Integer = dataset3.Tables(0).Rows.Count
If count9 > 0 Then
Also, make sure one of the check-boxes (CheckBox1 or CheckBox2) mentioned later in your code is ticked.
-- EDIT --
Sorry - didn't explain why! The reason is that the majority of array/list like structures in .NET are zero based (i.e. start counting from 0 instead of 1).
The best course of action for you is to maximize your productivity by allowing SQL to do what it does best. Assuming you are using SQL Server 2008, the MERGE function is an excellent use case for the conditions that you have supplied.
Here is a very basic example that is contrived based upon some of your code:
CREATE PROCEDURE [dbo].[csp_Medical_Merge]
#MType int, #FileNo varchar(20), #MNotes varchar(max), #ID int, #OtherParams
AS
BEGIN
MERGE INTO [DatabaseName].dbo.Medical AS DEST
USING
(
/*
Only deal with data that has changed. If nothing has changed,
then move on.
*/
SELECt #MType, #MNotes, #FileNo, #ID, #OtherParams
EXCEPT
Select [Type], MNotes, FileNo, ID, OtherFields from [DatabaseName].dbo.Medical
) As SRC ON SRC.ID = DEST.ID
WHEN MATCHED THEN
UPDATE SET
DEST.MNOTES = SRC.MNOTES,
DEST.FileNo = SRC.FileNo,
DEST.Type = SRC.Type
WHEN NOT MATCHED BY TARGET THEN
INSERT (FieldsList)
VALUEs (FileNo, MNotes, etc, etc);
END
GO

Report only shows the last record

I have to display data from VB.NET code to crystal report...and I'm doing everything from the code, so the problem is that I have to display multiple data from for-each loop, this is the code:
Private Sub Print_Row(ByVal pp As Boolean)
Dim rptDokument As New ReportDocument, brkop As Integer
Dim rw_mat As DataRow
Dim cn As OracleClient.OracleConnection = New OracleClient.OracleConnection(Gdb_conn)
' Objects used to set the parameters in the report
Dim pCollection As New CrystalDecisions.Shared.ParameterValues
Dim pTSJ As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pNaziv As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pKolicina As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pTezina As New CrystalDecisions.Shared.ParameterDiscreteValue
Try
rptDokument.Load(Gpath & "PakLista.rpt")
pTSJ.Value = barcode.Text
pCollection.Add(pTSJ)
rptDokument.DataDefinition.ParameterFields("pTSJ").ApplyCurrentValues(pCollection)
cn.Open()
Dim myQuery As String = "SELECT S.TSJ,M.NAZ_MAT, S.IBRMAT, S.KOLICINA, S.TEZINA " & _
"FROM TWM_SADRZAJ S, TWM_MATER M, TWM_ATRIBUT A, TWM_PAKIR PAK " & _
"WHERE(S.VLASNIK_MP = M.VLASNIK_MP) " & _
"AND S.IBRMAT = M.IBRMAT " & _
"AND S.ATR_ID = A.ATR_ID (+) " & _
"AND PAK.VLASNIK_MP (+) = S.VLASNIK_MP " & _
"AND PAK.IBRMAT (+) = S.IBRMAT " & _
"AND PAK.PAK (+) = S.PAK " & _
"AND (S.TSJ = '" & barcode.Text & "') " & _
"ORDER BY S.IBRMAT"
Dim da As OracleClient.OracleDataAdapter = New OracleClient.OracleDataAdapter(myQuery, cn)
Dim ds As New DataSet
da.Fill(ds, "TWM_SADRZAJ")
For Each rw_mat In ds.Tables("TWM_SADRZAJ").Rows
If (rw_mat.Item("NAZ_MAT") Is DBNull.Value) Then
pNaziv.Value = ""
Else
pNaziv.Value = CStr(rw_mat.Item("NAZ_MAT"))
End If
If (rw_mat.Item("KOLICINA") Is DBNull.Value) Then
pKolicina.Value = ""
Else
pKolicina.Value = CStr(rw_mat.Item("KOLICINA"))
End If
If (rw_mat.Item("TEZINA") Is DBNull.Value) Then
pTezina.Value = ""
Else
pTezina.Value = CStr(rw_mat.Item("TEZINA"))
End If
pCollection.Add(pNaziv)
rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina)
rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina)
rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
Next rw_mat
If pp Then
Dim frm As New frmPrint_preview
frm.crvDocument.ReportSource = rptDokument
frm.ShowDialog()
Else
Dim pd As New PrintDialog
pd.PrinterSettings = New PrinterSettings
If pd.ShowDialog(Me) Then
For brkop = 1 To pd.PrinterSettings.Copies
rptDokument.PrintOptions.PrinterName = pd.PrinterSettings.PrinterName
rptDokument.PrintToPrinter(1, False, 1, 99999)
Next brkop
End If
End If
Catch Exp As LoadSaveReportException
MsgBox("Incorrect path for loading report.", MsgBoxStyle.Critical, "Load Report Error")
Catch Exp As System.Exception
MsgBox(Exp.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
The problem is in this section:
pCollection.Add(pNaziv) rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina) rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina) rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
It has to be out side for each loop to gather all the data, but the problem is no mater where i put this code it only displays the last record from data row for let's say 5 records in crystal report...I know it's peace of cake but I'm relay stuck here so I would appreciate a little help.
It is normal that the report only shows the last record, because you try to pass the data as parameters. Instead you should set the datasource programmatically, you can see how to do it here ^
ReportDocument.SetDataSource Method
and here you can find a complete example of how to create a typed dataset to use on your report
Create report by vb.net and crystal report

ODBC - unable to allocate an environment handle

Hi I am trying to insert data into Navision database from a DataTable. That DataTable contain around 5000 records, if the records count is less then it's working fine but record count is around 5000 I am getting this error.
ERROR - unable to allocate an environment handle.
This is the code I am using
Public Function InsertToHHTTransferLine(ByVal dtTransferLn As DataTable, ByVal hhtNumber As String) As Integer
Dim result As Integer
Dim cn As OdbcConnection
Dim dtTransferLine As DataTable
cn = New OdbcConnection(ConnStr)
Dim SqlStr As String = ""
Try
cn.Open()
dtTransferLine = dtTransferLn
Dim DocType As String
DocType = "Purchase"
Dim cmd As OdbcCommand
Dim hhtNo As String
hhtNo = hhtNumber
If dtTransferLine.Rows.Count > 0 Then
For i As Integer = 0 To dtTransferLine.Rows.Count - 1
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "0" Then
DocType = "Purchase"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "1" Then
DocType = "Transfer Receipt"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "2" Then
DocType = "Transfer Shipment"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "3" Then
DocType = "Stock Count"
End If
Try
SqlStr = "INSERT INTO ""HHT & Navision Line""(""Document Type"",""Document No_"",""HHT No_"",""Line No_"",""Item No_"",""Document Quantity"",""Scan Quantity"",""Unit Price"",""Posted"") VALUES('" & DocType & "','" & dtTransferLine.Rows(i)("DOC_NO").ToString() & "','" & hhtNo & "','" & dtTransferLine.Rows(i)("LINE_NO").ToString() & "','" & dtTransferLine.Rows(i)("ITEM_NO").ToString() & "'," & dtTransferLine.Rows(i)("DOC_QTY").ToString() & "," & dtTransferLine.Rows(i)("SCAN_QTY").ToString() & "," & dtTransferLine.Rows(i)("UNIT_PRICE").ToString() & ",0)"
cmd = New OdbcCommand(SqlStr, cn)
result = cmd.ExecuteNonQuery()
Catch ex As Exception
If (ex.Message.IndexOf("Illegal duplicate key") <> -1) Then
CreateLog(SqlStr, "User1", "Duplicate()", ex.Message)
Else
CreateLog(SqlStr, "User1", "Other()", ex.Message)
End If
'CreateLog(SqlStr, "User1", "Other()", ex.Message)
End Try
Next
End If
Catch ex As Exception
CreateLog(SqlStr, "User1", "InsertToHHTTransferLine()", ex.Message)
result = -1
Finally
cn.Close()
cn.Dispose()
End Try
Return result
End Function
Could be that "cmd" variables need to be disposed before creating new ones?
At least this is the only thing I can see in the code where you are consuming resources in a loop depending on the number of records.
Anyway this should be easy to identify with a debugger, just figure out the line giving you the error, and that will lead you to the answer.

How Insert datetime from datagridview to database? VB.NET

i want Insert datetime from datagridview to database.But i'm don't save required.
Ex.
Datagridview
DAte
2012-11-20 16:36:39
when i'm save to datagridview to datebase
DAte
1900-01-01 00:00:00.000
I want save 2012-11-20 16:36:39 to dataasbe but it's don't result.
Show Datagridview
Dim sqlSentMaterial As String = ""
Dim DT_SentMaterial As New DataTable
sqlSentMaterial = "SELECT rc.No,rc.ReceiveDate as RCReceiveDate,rc.CreateBy as RCReceiveBy,rc.CreateDate,rc.ReceiveNote "
sqlSentMaterial &= "FROM RClother rc "
sqlSentMaterial &= "Where rc.No ='" & Search & "'"
DT_SentMaterial = FShowData(sqlSentMaterial)
For i As Integer = 0 To DT_SentMaterial.Rows.Count - 1
If DT_SentMaterial.Rows.Count <> 0 Then
Dim item As New DataGridViewRow
item.CreateCells(DgvSentMaterial)
With item
.Cells(1).Value = TxtBarcode.Text
If DT_SentMaterial.Rows(0).Item("RCReceiveDate") Is DBNull.Value Then
.Cells(2).Value = ""
Else
.Cells(2).Value = CDate(DT_SentMaterial.Rows(0).Item("RCReceiveDate")).ToString("dd/MM/yyyy")
End If
End With
DgvSentMaterial.Rows.Add(item)
Exit For
End If
Next
Form save datagridview to database
Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
Dim sentMat As Integer
sentMat = FInsertSentMatClother(CInt(DgvSentMaterial.Rows(i).Cells(1).Value), CDate(DgvSentMaterial.Rows(i).Cells(2).Value))
End Sub
Function Insert To Database
Public Function FInsert_iPOSentMatClother(ByVal BarCode As Integer, ByVal RCReceiveDate As Date)
Dim Tr As SqlTransaction
Dim sqlCom As New SqlCommand
Dim sqlInsert As String
Dim ReturnValue As Integer
Dim GetDate As DateTime = DateTime.Now
Try
Tr = Conn.BeginTransaction
sqlCom.Connection = Conn
sqlInsert = "INSERT INTO SentMatClother "
sqlInsert &= "(BarCode,ReceiveDate) "
sqlInsert &= "VALUES('" & BarCode & "','" & RCReceiveDate & "')"
sqlCom.Transaction = Tr
sqlCom.CommandText = sqlInsert
sqlCom.CommandType = CommandType.Text
ReturnValue = CInt(sqlCom.ExecuteScalar) 'CInt(sqlCom.ExecuteScalar)
If ReturnValue = 0 Then
Tr.Commit()
Else
Tr.Rollback()
End If
Catch ex As Exception
'MsgBox(ex.ToString)
Finally
If Not sqlCom Is Nothing Then
sqlCom.Dispose()
End If
sqlCom = Nothing
End Try
Return ReturnValue
End Function
Thanks you for you time. :)
in your Function insert to database just format Date value in string as you want
sqlInsert = "INSERT INTO SentMatClother "
sqlInsert &= "(BarCode,ReceiveDate) "
sqlInsert &= "VALUES('" & BarCode & "','" & RCReceiveDate.ToString("yyyy-MM-dd HH:mm:ss") & "')"
or and on my opinion is a better practice using a parameters:
sqlInsert = "INSERT INTO SentMatClother (BarCode,ReceiveDate) VALUES (#barCode, #receiveDate)"
//then add parameters to your sqlCommand
sqlCom.Parameters.AddWithValue("#barCode", BarCode)
sqlCom.Parameters.AddWithValue("#barCode", RCReceiveDate)

Data Reader formatting output

I'm using the following function to generate a list of users connected to a selected database. How would I change this to a single line for multiple identical results?
For example: "sa (3) - MYCOMPUTER" rather than listing "sa - MYCOMPUTER" three times?
Function ConnectedUsers(ByVal SelectedDatabase As String, ByVal SelectedInstance As String)
Dim myCommand As SqlCommand
Dim dr As SqlDataReader
Dim mystring As String = String.Empty
Try
Dim myConn As New SqlConnection(ConnectionString)
myConn.Open()
myCommand = New SqlCommand("select loginame,hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & ";", myConn)
dr = myCommand.ExecuteReader()
While dr.Read()
mystring += GetFullName(dr(0).ToString().Trim()) & " - " & dr(1).Trim() & vbCrLf
End While
dr.Close()
myConn.Close()
Catch e As Exception
MessageBox.Show(e.Message)
End Try
Return mystring
End Function
Thanks.
The SQL Command should be
select loginame, count(*) as Nbr, hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & "' group by loginame;"
and you should change the display to show the count (Nbr in this example) to be something like:
mystring += GetFullName(dr(0).ToString().Trim()) & "(" & dr(1).Trim() & ") - " & dr(2).Trim() & vbCrLf