This is my first time asking a question and I've been searching for 2 days to find an answer. Hopefully one of you masters can assist.
I have a 4 column listview populated from a sql table. The table doesn't allow duplicates. I simply want to be able to catch that error and give a friendly message to the user that the item is already in the list. I have found multiple solutions that don't work (probably my error).
Below is the one that I had the most hope for... but nothing.
Still getting "Violation of PRIMARY KEY constraint 'PK_tbl.associateNames'. Cannot insert duplicate key in object 'dbo.tbl.associateNames'.
The statement has been terminated"
Protected Sub listviewInserting_itemInserted(ByVal sender As Object, ByVal e As ListViewInsertEventArgs)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=server\instance; Initial Catalog=sears;User Id=johnnyFive;Password=alive;"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO [tbl.associateNames] ([orderIssuer], [associateName], [department]) VALUES (#orderIssuer, #associateName, #department)"
cmd.ExecuteNonQuery()
Catch ex As SqlException
MsgBox("Duplicate Entry found", MsgBoxStyle.Information, "Dups")
e.Cancel = True
End Try
End Sub
ANY suggestions would be appreciated! Thanks.
Should work. Perhaps the wrong type of execption? What happens if you enlarge the catch to
Catch ex As Exception
I am officially an idiot.
Had I remembered to put this line like this (i.e. add the Handles blah blah) I wouldn't have had the issue.
Protected Sub listviewInserting_itemInserted(ByVal sender As Object, e As ListViewInsertEventArgs) Handles ListView1.ItemInserting
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Related
I'm a VB.NET programmer. I have created an update web form in ASP.NET having 3 fields; ID, Names, Email with 3 buttons cmdUpdate, cmdDelete and cmdCancel. All are executing except for the update button which is not executing, and I can't get an error message either. The code is below.
Protected Sub cmdUpdate_Click(sender As Object, e As EventArgs) Handles cmdUpdate.Click
Dim conn As New SqlClient.SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=RegDb_backend;Integrated security=true;")
Dim sql As String = "UPDATE tblClients SET ClientNames=#Names, ClientEmail=#Email WHERE ClientID=#ID;"
Dim cmd = New SqlClient.SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter("#Names", txtNames.Text.Trim()))
cmd.Parameters.Add(New SqlParameter("#Email", txtEmail.Text.Trim()))
cmd.Parameters.Add(New SqlParameter("#ID", Convert.ToInt64(txtID.Text.Trim)))
Try
conn.Open()
cmd.ExecuteNonQuery()
lblSuccess.Visible = True
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I have tried researching and tweaking around with the code but the database won't get updated. Please help. Thank you.
Sorry if this question is stupid but I have no other way to see the big picture.
I have 1 textbox, 1 label and database with two columns (codename and description), by entering codename in textbox I would like to get corresponding description in label.
With Excel and VBA it can be done with couple of lines. Sadly I can not use Excel but have to choose Web interface 'cause of slow PCs and Office price. Why is this simple task so complicated in ASP.NET with all general declarations and sqlservers and sqlconnections.
Is there a simpler way to do this?
BTW. I've tried to adapt many different things I've found on the web and this last one looks promising but it doesn't work :
Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Using sqlconn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=KLIJENTI;Integrated Security=True"), _
sqlcmd As New SqlCommand("Select From Baza Where SIFRE = #SIFRE", sqlconn)
sqlcmd.Parameters.Add("#SIFRE", SqlDbType.VarChar, 50).Value = TextBox2.Text
sqlconn.Open()
'Label1.Text = CString(sqlcmd.ExecuteScalar()) 'CString is not declared
Label1.Text = sqlcmd.ExecuteScalar()
End Using
End Sub
Where Baza is Table name,
SIFRE is codename that will be entered in textbox
and NAZIV is description corresponding to SIFRE and should be shown in Label
The correct form is
Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Using sqlconn = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=KLIJENTI;Integrated Security=True")
Using sqlcmd = New SqlCommand("Select NAZIV From Baza Where SIFRE = #SIFRE", sqlconn)
sqlcmd.Parameters.AddWithValue("#SIFRE", TextBox2.Text)
sqlconn.Open()
Dim result = sqlcmd.ExecuteScalar()
if result IsNot Nothing Then
Label1.Text = result.ToString
End If
End Using
End Using
End Sub
The SELECT sql clause is followed by the list of columns you want to retrieve. (Added NAZIV)
Also you should consider that your query could not find a value for the parameter #Sifre and, in that case, the result of the ExecuteScalar is Nothing.
Please have a look at the code below, which I have written as a test. It does not make the ASP.NET process grow too much:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim Test As Integer
For Test = 0 To 1000000
Test1()
Next
Dim Test2 As String = "Test"
Catch ex As Exception
End Try
End Sub
Public Sub Test1()
Try
Dim objCommand As New SqlCommand
Dim strConString As String = "Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True"
Dim objCon As New SqlConnection
objCon.ConnectionString = strConString
objCon.Open()
objCommand.Connection = objCon
objCommand.CommandText = "select * from person "
Dim objDR As SqlDataReader = objCommand.ExecuteReader
If objDR.HasRows Then
Using objCon
End Using
End If
Catch ex As Exception
'I don't swallow exceptions.
End Try
End Sub
End Class
I am trying to detect a memory leak. I have found code similar to the above in the affected project. I notice that objCommand.dispose is not called. The project in question connects to an Oracle database and an SQL database. When connecting to an SQL database the above code is used. When connecting to an Oracle database Oracle.dataaccess.dll is used and the code looks different to reflect this.
My specific question is: if I avoid calling sqlcommand.dispose then will this cause a memory leak over time?
If a class has a Dispose method, that isn't getting called, then it is likely to be the source of a memory leak. Use Using, and it will call the Dispose method for you.
Your second example should look like the below, where all disposable object are wrapped in using blocks.
Dim strConString As String = "Data Source=IANSCOMPUTER;" +
"Initial Catalog=Test;Integrated Security=True"
Dim sqlStr as String = "select * from person "
Using objCon As New SqlConnection(strConString)
Using objCommand As New SqlCommand(sqlStr, objCon)
objCon.Open()
Using objDR As SqlDataReader = objCommand.ExecuteReader
If objDR.HasRows Then
End If
End Using
End Using
End Using
In codebehind I have the following:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
Dim sql As String
Dim conn As OleDbConnection
Dim cmd As OleDbDataAdapter
Dim ds As DataSet
Dim tbl As DataTable
conn = New OleDbConnection("Provider=SQLOLEDB;Data Source=(local);Initial Catalog='library';Integrated Security=SSPI;")
Try
sql = "SELECT f1, f2, f3 FROM mydb WHERE ltrim(rtrim(UPPER(username))) = 'MYNAME'"
cmd = New OleDbDataAdapter(sql, conn)
ds = New DataSet
cmd.Fill(ds)
tbl = New DataTable
tbl = ds.Tables(0)
If tbl.Rows.Count = 0 Then
Response.Redirect("goback.html")
End If
Response.Redirect("dummy.html")
Catch ex As Exception
Response.Redirect("goback2.html")
End Try
End Sub
The routine works to a point. I can check the value of tbl.Rows.Count = 1, so it should redirect to "dummy.html" WHICH IT DOES CORRECTLY so long as I comment out the line that redirects to "goback2.html".
If I uncomment the line to redirect to goback2, then it goes to "goback2.html"
I thought it should only execute that code if there was some error in the previous code - but there can't be an error in the previous code, if it executes. It's like it's executing the catch code regardless of what I'm going.
Oddly, it ONLY messes up with the redirect! If I replace the redirect to goback2 with an assignment to a textbox.text then it works (by ignoring that code) - but the redirect it seems to execute regardless of whether it should take the catch
Response.Redirect(string) throws a ThreadAbortException when Response.End() is called.
Use the overload that takes a string and a boolean instead:
Response.Redirect("goback.html", false);
From MSDN: the second parameter, endResponse, "Indicates whether execution of the current page should terminate."
Response.Redirect throws a ThreadAbortException to terminate the current request.
Your Catch block is catching that exception.
It may be because of ThreadAbortedException because of Response.Redirect. - MSDN support link
You haven't open the connection. You cannot redirect in an Try/Catch. You should set a boolean variable success to false and check for it after the Try/Catch/Finally and redirect if it's set to false.
Have a look at this SO-Question: Is there something that prevents Response.Redirect to work inside try-catch block?
This would be better:
Dim success As Boolean = True
Dim ds As New DataSet
Using conn As New OleDb.OleDbConnection("Provider=SQLOLEDB;Data Source=(local);Initial Catalog='library';Integrated Security=SSPI;")
Try
Dim Sql = "SELECT f1, f2, f3 FROM mydb WHERE ltrim(rtrim(UPPER(username))) = 'MYNAME'"
Dim cmd = New OleDb.OleDbDataAdapter(Sql, conn)
conn.Open()
cmd.Fill(ds)
Catch ex As Exception
success = False
End Try
End Using
If Not success Then
Response.Redirect("goback2.html")
ElseIf ds.Tables.Count <> 0 AndAlso ds.Tables(0).Rows.Count = 0 Then
Response.Redirect("goback.html")
Else
Response.Redirect("dummy.html")
End If
I made a basic program that connects and gets content from a table via SQL, it's working normally. What I want is; when connection losts via SQL Server or internet connection, it must continue to list items that it got before connection losts instead of giving "Connection Problem Error".
Code is like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strSQL As String
Dim conn As New SqlConnection
conn.ConnectionString = baglan()
conn.Open()
strSQL = "SELECT * FROM Telefon_Otomasyon"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim dset As New DataSet()
da.Fill(dset, "Telefon_Otomasyon")
Dim Hepsi As DataRow
For Each Hepsi In dset.Tables("Telefon_Otomasyon").Rows
Response.Write(Hepsi("Arayan") & "<br />")
Next
End Sub
Thanks!
What you can do is store your dataset in Session: (excuse my VB, i'm very rusty with it)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strSQL As String
Dim conn As New SqlConnection
conn.ConnectionString = baglan()
conn.Open()
strSQL = "SELECT * FROM Telefon_Otomasyon"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim dset As New DataSet()
Try
da.Fill(dset, "Telefon_Otomasyon")
MyDataset = dset
Catch ex As SqlException
dset = MyDataset
End Try
Dim Hepsi As DataRow
For Each Hepsi In dset.Tables("Telefon_Otomasyon").Rows
Response.Write(Hepsi("Arayan") & "<br />")
Next
End Sub
Private Property MyDataset() As DataSet
Get
return Session("myDataset")
End Get
Set(ByVal value as DataSet)
Session("myDataset") = value
End Set
End Property
This is also a very basic example, it needs to be tidied up before you can use it in production code, i.e. you need to consider what to do if there is no dataset stored in Session (if it returns null). You may want to be a bit smarter than that and just store a specific table. Note that Session can expire though, so do some reading on it. This should be enough to steer you in the right direction.
Further note: if you want something a little less volatile than Session then you could try using the Cache instead.
I'm not sure I understand the problem here. While I'm not a VB-programmer it seems to me like once the page loads it will run the SQL query and then process that dataset.
If you reload the page and the SQL connection isn't working you will get an error that you'd need to handle somehow (not sure how VB exceptions work but I'm sure you can figure that out).
If you on the other hand mean that you want to get whatever data you can from a query that gets disconnected mid-query - I'd say that is pretty hard and only relevant for huge queries.