The issue that i'm having is that trhough a button1 upon click shall save the data entered in the textboxes (see code) however when the page is postback the data is not saved (no confirmation message appears) then if i click again it does saves the record, sometimes takes more than 3 times until the data is stored per confirmation message.
Is this a Con.Dispose Issue??? Shall i use con.close?
Note: in the code i have Con.CLOSE however the page is deployed under Con.Dispose()
Note2: i'm planning to fix more "novice" issues found in the code but urgent question remains in the postback issue.
' *--------Empty Text Validation-------*
If TextBox10_AddData_LabInvest.Text <> "" AndAlso TextBox3_AddData_LabInvest.Text <> "" AndAlso TextBox4_AddData_LabInvest.Text <> "" AndAlso TextBox5_AddData_LabInvest.Text <> "" AndAlso TextBox6_AddData_LabInvest.Text <> "" AndAlso TextBox7_AddData_LabInvest.Text <> "" Then
' *--------SQL Insert command-------*
SqlDataSource_AddData_LabInvest.InsertCommand = "INSERT INTO [LabInvest] (ID_LabInvest, LabInvest_Load, LabInvest_SeqRef_CH, LabInvest_SeqRef_Year, LabInvest_Owner, LabInvest_Subject, LabInvest_DueDate, LabInvest_Code, LabInvest_QSNCCode, LabInvest_OpenByOwner, LabInvest_OpenDateOwner, Status_Text, Status_Int ) VALUES(#ID_LabInvest, #LabInvest_Load, #LabInvest_SeqRef_CH, #LabInvest_SeqRef_Year, #LabInvest_Owner, #LabInvest_Subject, #LabInvest_DueDate, #LabInvest_Code, #LabInvest_QSNCCode, #LabInvest_OpenByOwner, #LabInvest_OpenDateOwner, #Status_Text, #Status_Int)"
SqlDataSource_AddData_LabInvest.InsertParameters.Add("ID_LabInvest", TextBox10_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Load", "N/A")
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_SeqRef_CH", TextBox1_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_SeqRef_Year", TextBox2_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Owner", TextBox3_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Subject", TextBox4_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_DueDate", TextBox5_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Code", TextBox6_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_QSNCCode", TextBox7_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_OpenByOwner", TextBox8_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_OpenDateOwner", TextBox9_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("Status_Text", "Stage 1 - Just Added")
SqlDataSource_AddData_LabInvest.InsertParameters.Add("Status_Int", "1")
Try
SqlDataSource_AddData_LabInvest.Insert()
' *--------Get Unique ID-------*
Dim Con As New SqlConnection
Dim SQL As String
Dim com As SqlCommand = Con.CreateCommand
Con.ConnectionString = "removed"
Con.Open()
SQL = "SELECT ID_LabInvest FROM LabInvest WHERE ID_LabInvest=" + TextBox10_AddData_LabInvest.Text
Dim cmd As New SqlCommand(SQL, Con)
Dim obj = cmd.ExecuteScalar()
Label1_AddData_LabInvest.Text = "Your record ID is: " + obj.ToString()
' *--------Get Stage-------*
Dim SQL2 As String
SQL2 = "SELECT Status_Text from LabInvest WHERE ID_LabInvest=" & obj
Dim cmd2 As New SqlCommand(SQL2, Con)
Dim obj2 = cmd2.ExecuteScalar()
Label2_AddData_LabInvest.Text = "Record Stage: " + obj2.ToString()
con.close()
Button4_AddData_LabInvest.Enabled = False
' *--------SQL Audit Insert command-------*
Dim Usercheck As String
Usercheck = Request.ServerVariables("LOGON_USER")
SqlDataSource_LabInvest_Audit.InsertCommand = "INSERT INTO [AuditTrial] (ID_Table, AuditTableName, AuditAction, AuditUser, AuditValue1Before, AuditValue2Before, AuditValue1After, AuditValue2After, AuditMasterReason, AuditMasterChange) VALUES(#ID_Table, #AuditTableName, #AuditAction, #AuditUser, #AuditValue1Before, #AuditValue2Before, #AuditValue1After, #AuditValue2After, #AuditMasterReason, #AuditMasterChange)"
SqlDataSource_LabInvest_Audit.InsertParameters.Add("ID_Table", obj)
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditTableName", "LaboratoryInvestigations_Add")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditAction", "Added New Record")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditUser", Usercheck)
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue1Before", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue2Before", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue1After", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue2After", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditMasterReason", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditMasterChange", "N/A")
SqlDataSource_LabInvest_Audit.Insert()
Catch ex As Exception
Label1_AddData_LabInvest.Text = "Duplicate NumberID, Please Review Data"
End Try
Else
Label1_AddData_LabInvest.Text = "Please Fill All Options"
End If
The issue was found as the application was residing in a Web Servers Farm with NLB, therefore the blank post-back was due to the NBL redirecting the user to another server from the original connection. (different solutions may apply link NO Cache, Connection Affinity,etc) hope it helps someone in the future.
Related
So I am having a problem loading a drop down list in an asp.net web forms site. I am pulling the records from a SQL Server database. I am binding the results to a drop down list.
My problems stems from the fact that I am retrieving 21500 plus rows and it is causing a long delay to the point where the browser throws a message asking if I want to stop a long executing script. If I wait long enough, ~2 minutes it will come back but still runs very slow taking a long time scroll down through the list.
Here is the VB code for the SQL call:
Private Function GetCorInfo(field As String, tblname As String, Optional whereClause As String = "") As DataTable
Dim sqlCmdTxt As String = "Select " & field & " From " & tblname
Using conn As New SqlConnection(corConnection)
Try
conn.Open()
Catch ex As Exception
Master.message = "Unable to open SQL DB connection\nError: SQL101\nPlease contact the Help Desk for support.\n" & HttpUtility.JavaScriptStringEncode(ex.Message)
jsa.alertmessage(passedPage, Master.message)
End Try
Using sqlCmd As New SqlCommand
'Check for where clause
If whereClause <> "" Then
sqlCmdTxt = sqlCmdTxt & whereClause
If whereClause.Substring(7, 6) = "cornum" Then
sqlCmd.Parameters.AddWithValue("#cornum", ddl2.SelectedItem.Text)
End If
End If
If field = "cornum" Then
sqlCmdTxt = sqlCmdTxt & " Order By " & field & " Desc"
End If
sqlCmd.CommandText = sqlCmdTxt
sqlCmd.Connection = conn
Using sqlDT As New DataTable()
Using sqlDA As New SqlDataAdapter(sqlCmd)
Try
sqlDA.Fill(sqlDT)
Return sqlDT
Catch ex As Exception
conn.Close()
Master.message = "Unable to load list.\nError: SQL104\n" & HttpUtility.JavaScriptStringEncode(ex.Message)
jsa.alertmessage(passedPage, Master.message)
Return Nothing
End Try
End Using
End Using
End Using
End Using
End Function
Then when the data table is returned I am binding it to the drop down list using this code:
If Not IsNothing(dt) Then
'Set ddl
With ddl
'Turn on ddl
.Visible = True
'Set Data Source
.DataSource = dt
'Set Text Field
.DataTextField = field1
'Set Value Field
.DataValueField = field1
'Set variable to field value
'Bind Data
.DataBind()
'Assign Variable
field = ddl.SelectedItem.Text
'Check for ddl match
If whereClause <> "" AndAlso ddl1.SelectedIndex = 3 AndAlso ddl.ID = "ddl3" Then
.Items.FindByValue(field).Selected = True
ElseIf whereClause <> "" AndAlso ddl1.SelectedIndex = 3 AndAlso ddl.ID = "ddl4" Then
.Items.Insert(0, New ListItem("Select", "0"))
Else
'Insert first choice
.Items.Insert(0, New ListItem("Select", "0"))
End If
'Set to index 0
.SelectedIndex = 0
End With
Return 1
Else
Return -1
End If
Both sets of codes are run in functions.
How can I speed this up? I have looked at using Session and View State but the number of returned records would cause a bigger slow down if I do that.
Does anyone have any ideas?
Thanks in advance for the help.
So this what i finally did.
Placed a text box for the user to type in the first few char's of a new customer name. Then taking that I build a SQL query that only returns records that match the chars entered.
Much faster and only have at max 35 records...
I am trying to send some variables, using a session, to the next page "ProcedureSelectionForm.aspx". As you can see, the sessions have been commented out. The code below will work (without sending the variable of course). However, when you remove the comments the .onclick function reloads the page rather than navigating to "ProcedureSelectionForm.aspx". For this reason, I believe this is where my problem is. The first two columns are "Account" and "Password" in the database. I have not misspelled anything. I am new to VB and ASP.net and would appreciate some explanation as to what is happening and why my desired functionality isn't materializing. Thank you for your help!
If IsValid Then
Try
Dim strSQL = "select * from CreatePatient where Account = #Account and Password = #Password"
Using CCSQL = New SqlConnection(ConfigurationManager.ConnectionStrings("CreatePatientConnectionString").ConnectionString)
Using CCUser = New SqlCommand(strSQL, CCSQL)
CCSQL.Open()
CCUser.Parameters.Add("#Account", Data.SqlDbType.VarChar).Value = PatientAccount.Text
CCUser.Parameters.Add("#Password", Data.SqlDbType.VarChar).Value = PatientPass.Text
CCUser.ExecuteNonQuery()
'Using reader As SqlDataReader = CCUser.ExecuteReader()
'If reader.HasRows Then
'reader.Read()
'Session("user") = reader("Account")
'Session("pass") = reader("Password")
Response.Redirect("ProcedureSelectionForm.aspx")
'End If
'End Using
End Using
End Using
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
My friend was able to make time to help me out. I am unsure of what he did differently besides closing connections
If IsValid Then
Dim CCSQL As New SqlConnection
Dim CCUser As New SqlCommand
Dim strSQL As String
Dim dtrUser As SqlDataReader
Try
CCSQL.ConnectionString = ConfigurationManager.ConnectionStrings("CreatePatientConnectionString").ConnectionString
strSQL = "Select * from CreatePatient where Account=#user and Password=#pwd"
CCUser.CommandType = Data.CommandType.Text
CCUser.CommandText = strSQL
CCUser.Parameters.Add("#user", Data.SqlDbType.VarChar).Value = PatientAccount.Text
CCUser.Parameters.Add("#pwd", Data.SqlDbType.VarChar).Value = PatientPass.Text
CCSQL.Open()
CCUser.Connection = CCSQL
dtrUser = CCUser.ExecuteReader()
If dtrUser.HasRows Then
dtrUser.Read()
Session("user") = dtrUser("Account")
Session("level") = dtrUser("Password")
Response.Redirect("ProcedureSelectionForm.aspx")
Else
Label1.Text = "Please check your user name and password"
End If
dtrUser.Close()
CCSQL.Close()
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
I am on a tight deadline but i will get back to those interested with an answer. Thank you for your effort.
You don't want to do .ExecuteNonQuery() when you are actually doing a query (i.e. a SQL "SELECT" statement. You can just do the .ExecuteReader() to read those two values.
Also, I presume you are trying to validate the Account and Password; otherwise you could just set Session("user") = PatientAccount.Text and set Session("pass") = PatientPass.Text.
I have been working on this particular issue for a couple of days, and scouring over SO, MSDN and other google searches has not proven to be of any use. I am trying to make a simple update to a SQL table. My SELECT and INSERT statements all work fine, but for some reason, this update will not work. I have set breakpoints and stepped through, and the code seems to be working fine -- the Catch ex as Exception is never reached after the .ExecuteNonQuery() fires off.
Could anyone give me an idea of why I've been unable to get a SQL update?
Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim currentUser = Membership.GetUser(User.Identity.Name)
Dim username As String = currentUser.UserName
Dim userId As Guid = currentUser.ProviderUserKey
UserNameTextBox.Text = username
' Get Root Web Config Connection String so you don't have to encrypt it
Dim rootWebConfig As System.Configuration.Configuration
rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/")
Dim connString As System.Configuration.ConnectionStringSettings
connString = rootWebConfig.ConnectionStrings.ConnectionStrings("LocalSqlServer")
Dim conn As String = connString.ToString
Dim commandString As String = "UPDATE UserDetails SET FirstName ='" + FirstNameTextBox.Text + "' WHERE UserId ='" + userId.ToString + "'"
Dim fname As String = FirstNameTextBox.Text
Dim commandText As String = "UPDATE UserDetails SET FirstName=#firstname WHERE UserId=#UID;"
Using connection As New SqlConnection(conn)
Dim command As New SqlCommand(commandText, connection)
command.CommandType = CommandType.Text
' Add UserId parameter for WHERE clause.
command.Parameters.Add("#UID", SqlDbType.UniqueIdentifier).Value = userId
' command.Parameters("#UID").Value = userId
' command.Parameters.AddWithValue("#UID", userId)
' Use AddWithValue to assign Demographics.
command.Parameters.Add("#firstname", SqlDbType.VarChar, 255).Value = fname
'command.Parameters.AddWithValue("#firstname", fname)
' command.Parameters("#firstname").Value = FirstNameTextBox.Text.ToString
Try
connection.Open()
command.ExecuteNonQuery()
Dim rowsAffected As Integer = command.ExecuteNonQuery()
Console.WriteLine("RowsAffected: {0}", rowsAffected)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
You're running "command.ExecuteNonQuery()" twice, meaning the second execution will likely return 0 rows affected since you already updated what you needed to update, and that's what you're assigning to rowsAffected. Are you sure the UPDATE isn't occurring?
Edit: Re your comment, did you check for IsPostBack when you LoadUser? If not, when you click SaveButton, you're going to reload the existing values, and then you'll be updating with those existing values.
I am not sure why this code doesn't work
I have follow according to the table field data and it I am still unable to get the SQL Datareader to work. I have checked the tables and all datafields, everything is correct. But I still am unable to read data from the database. Help T.T
Dim connectionString = ConfigurationManager.ConnectionStrings("CleanOneConnectionString").ConnectionString
Dim myConn As New SqlConnection(connectionString)
myConn.Open()
Dim cmd = "Select * from [Member] where Email = #Email"
Dim myCmd As New SqlCommand(cmd, myConn)
myCmd.Parameters.AddWithValue("#Email", emailBox.Text)
Dim objReader As SqlDataReader
objReader = myCmd.ExecuteReader()
objReader.Read()
Result.Text = " " 'initialise label to show correct message for available or found
'Check the reader see if any record found matching WHERE
If (objReader.Read()) Then
'read=true, check Password
'Dim tpassword As String = objReader.GetString(5)
'If tpassword = passwordBox.Text Then
'Result.Text = "** Login Succcessful **"
Result.Text = objReader.GetString(1)
'Else
'Result.Text = "Invalid Password" & objReader.GetString(5) & passwordBox.Text
'End If
'reader=false, no such records matching WHERE
Else
Result.Text = objReader.GetString(1)
End If
myCmd.Dispose()
myConn.Dispose()
Testing with MySql: I get an error that the SQL syntax is not correct.
I then removed the [ ] and it works.
How is that with SqlServer? Try at least, i'd say.
I am using ASP.NET forms version 3.5 in VB
I have a dropdownlist that is filled with data from a DB with a list of countries
The code for the dropdown list is
<label class="ob_label">
<asp:DropDownList ID="lstCountry" runat="server" CssClass="ob_forminput">
</asp:DropDownList>
Country*</label>
And the code that the list is
Dim selectSQL As String = "exec dbo.*******************"
' Define the ADO.NET objects.
Dim con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand(selectSQL, con)
Dim reader As SqlDataReader
' Try to open database and read information.
Try
con.Open()
reader = cmd.ExecuteReader()
' For each item, add the author name to the displayed
' list box text, and store the unique ID in the Value property.
Do While reader.Read()
Dim newItem As New ListItem()
newItem.Text = reader("AllSites_Countries_Name")
newItem.Value = reader("AllSites_Countries_Id")
CType(LoginViewCart.FindControl("lstCountry"), DropDownList).Items.Add(newItem)
Loop
reader.Close()
CType(LoginViewCart.FindControl("lstCountry"), DropDownList).SelectedValue = 182
Catch Err As Exception
Response.Redirect("~/error-on-page/")
MailSender.SendMailMessage("*********************", "", "", OrangeBoxSiteId.SiteName & " Error Catcher", "<p>Error in sub FillCountry</p><p>Error on page:" & HttpContext.Current.Request.Url.AbsoluteUri & "</p><p>Error details: " & Err.Message & "</p>")
Response.Redirect("~/error-on-page/")
Finally
con.Close()
End Try
When the form is submitted an error occurs which says that the string "" cannot be converted to the datatype integer. For some reason the dropdownlist is posting "" rather than the value for the selected country.
2 things I can think of.
1) Are you sure the SQL is returning something that has the value of 182 ?
2) Are you rebuilding the Drop-down list on Postback ? as it's dynamic you'll have too else it won't know which value you selected.