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...
Related
Ok so what I'm trying to do is allow the users of my web form in asp.net to select multiple assets from a list box. When they select these assets and press the select button it fires the following code which should run through the selected indices, query the DB for the description and asset tag's, and populate the Description and Asset tag boxes with those values. Working through this I've been able to get it to read the values from the database and populate the fields but it would only populate the value from the first selected item and it would just insert the same value equal to the number of times equal to the number of items selected in the inbox. I tried my current code to run through the indices a little better but it seems to be failing the If statement and I just can't figure out why. Any help is appreciated, thanks everyone!
Dim i As Integer
For i = 0 To lstAssets.GetSelectedIndices.Count
If lstAssets.Items(i).Selected = True Then
Dim str2 As String = lstAssets.Items(i).Value.ToString
Dim cs As New OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings("CSIWebUpd").ConnectionString)
Dim ds As String = cs.DataSource
Dim cn As OracleConnection = New OracleConnection("user id=webupd;password=webupd;data source=" + ds)
Dim sql As String = "SELECT description, tag FROM assets WHERE id = :id"
Dim cmd As New OracleCommand(sql, cn)
cmd.Parameters.Add(":id", OracleDbType.Varchar2).Value = str2
cmd.CommandType = CommandType.Text
cmd.BindByName = True
cn.Open()
Dim dr As OracleDataReader = cmd.ExecuteReader()
cmd.ExecuteNonQuery()
dr.Read()
desc = dr.GetString(0).ToString
ass = dr.GetString(1).ToString
If txtDescription.Text = Nothing Then
txtDescription.Text = dr.GetString(0).ToString
Else
txtDescription.Text = txtDescription.Text + Chr(13) + Chr(10) + dr.GetString(0).ToString
End If
If txtAsset.Text = Nothing Then
txtAsset.Text = dr.GetString(1).ToString
Else
txtAsset.Text = txtAsset.Text + Chr(13) + Chr(10) + dr.GetString(1).ToString
End If
cmd.Dispose()
cn.Close()
End If
Next i
UpdatePanel1.UpdateMode = UpdatePanelUpdateMode.Conditional
UpdatePanel1.Update()
I would work with the SelectedIndices values in this way
For Each i in lstAssets.GetSelectedIndices
Now i contains the index of the items selected not the offset of the GetSelectedIndices array
The GetSelectedIndices returns an array where every element of the array is the index in the Items collection where you have an item selected.
An example could explain better:
Supposing the the items selected are 1, 5 6 (Count=3), your code set the value of i to 0,1,2 and then uses that value to lookup the ID in the items collection, but the following check on lstAssets.Items(i).Selected found just the item at index 1 as selected. Instead using the for each approach you get the values 1,5,6.
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.
I've been searching the depths of the internet and all the solutions I found did not solve this problem.
I am using Visual Web Developer 2010 Express with SQL Server 2008, using VB.
I am trying to execute a stored procedure to insert some data coming from a textbox control to a database, if the id doesn't exist it inserts both the id given in the textbox and the current date (time_scanned_in), if the id exists already, it will insert the current datetime in the [time_scanned_out] column, if all 3 fields in the db are full, it will return #message = 1.
Here is the sql stored procedure:
ALTER PROCEDURE dbo.InsertDateTime
#barcode_id nchar(20),
#message char(1) = 0 Output
AS
BEGIN
if not exists(select * from tblWork where barcode_id = #barcode_id)
begin
INSERT INTO [tblWork] ([barcode_id], [time_scanned]) VALUES (#barcode_id, GetDate())
end
else if exists(select * from tblWork where barcode_id = #barcode_id AND time_scanned_out IS NOT NULL )
begin
SET #message=1
end
else if exists(select * from tblWork where barcode_id = #barcode_id AND time_scanned_out IS NULL)
begin
UPDATE [tblWork] SET [time_scanned_out] = GetDate() WHERE [barcode_id] = #barcode_id
end
RETURN #message
end
If I execute this (by right clicking on the SP), it works flawlessly and returns the values when all fields have been filled.
But when executed through the vb code, no such procedure can be found, giving the error in the title.
Here is the vb code:
Dim opconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Dim sqlConnection1 As New SqlConnection(opconn)
Dim cmd As New SqlCommand
Dim returnValue As Object
cmd.CommandText = "InsertDateTime"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
With cmd.Parameters.Add(New SqlParameter("#barcode_id", TextBox.Text))
End With
With cmd.Parameters.Add(New SqlParameter("#message", SqlDbType.Char, 1, Label3.Text))
End With
returnValue = cmd.ExecuteScalar()
sqlConnection1.Close()
Note, I haven't done the code for the return part yet, will do that once I get it to locate the SP.
Tried listing all objects with the sys.objects.name for each of the databases in a gridview, it listed everything but the stored procedure I want.
Why is this, any ideas? Would be much appreciated, spent hours trying to find a solution.
If anyone needs any more code or information feel free to ask.
try cmd.parameters.clear() first and then start adding parameters in cmd object. also instead of cmd.executescaler(), try cmd.executenonquery or cmd.executeReader()
Try this
cmd.Parameters.AddWithValue("#barcode_id", TextBox.Text)
SqlParameter prmOut = cmd.Parameters.Add("#message",SqlDbType.Char, 1)
prmOut.Value = Label3.Text
prmOut.Direction = ParameterDirection.InputOutput
cmd.ExecuteNonQuery()
returnValue = prmOut.Value.ToString()
Recreated the whole project with a whole new database, copied all the same code, and now it all works flawlessly! Still have no idea what was wrong, but thank you all, you were all prompt and knowledgable.
Here was the final VB code for anyone who's interested:
Dim myConnection As New SqlConnection(opconn)
Dim cmd As New SqlCommand()
Dim myReader As SqlDataReader
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = myConnection
cmd.CommandText = "InsertTimes"
cmd.Parameters.AddWithValue("#message", OleDbType.Integer)
cmd.Parameters.AddWithValue("#barcode_id", TextBox.Text)
cmd.Parameters("#message").Direction = ParameterDirection.Output
Try
myConnection.Open()
myReader = cmd.ExecuteReader()
Dim returnMessage As String = cmd.Parameters("#message").Value
If returnMessage = 1 Then
label_confirmation.Text = "Record successfully submitted!"
TextBox.Text = ""
ElseIf returnMessage = 2 Then
label_confirmation.Text = "A finish time already exists for the record '" & TextBox.Text & "', would you like to override the finish time anyway?"
button_yes.Visible = True
button_no.Visible = True
ElseIf returnMessage = 3 Then
label_confirmation.Text = "Record submitted, work operation status complete!"
TextBox.Text = ""
End If
Catch ex As Exception
label_confirmation.Text = ex.ToString()
Finally
myConnection.Close()
End Try
i am making a website for trading, with trading feeds coming from a source in an excel sheet. I have to show data from the excel sheet in a gridview. When i make connection it will fail due to rapidly changing data; each cell in the sheet changes value 1-3 times per second. I am using an Ajax Timer of interval 100. Here is my code:
Public Function RetrieveExcelData(ByVal excelSheetName As String, ByVal sheetNumber As Integer) As DataSet
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
' Connection String.
Dim connString As [String] = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\Vishal\Desktop\TESTING COLOURfor web1.xls;Extended Properties=Excel 8.0;"
' Create connection object by using the preceding connection string.
objConn = New OleDbConnection(connString)
' Open connection with the database.
objConn.Open()
' Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
Dim i As Integer = 0
' Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
excelSheets(i) = row("TABLE_NAME").ToString()
i += 1
If i = sheetNumber Then
Exit For
End If
Next
Dim excelCommand As New OleDbCommand("Select * from [" + excelSheets(sheetNumber - 1) & "]", objConn)
Dim excelAdapter As New OleDbDataAdapter(excelCommand)
Dim excelDataSet As New DataSet()
excelAdapter.Fill(excelDataSet)
Return excelDataSet
Catch ex As OleDbException
Throw ex
Catch ex As Exception
Throw ex
Finally
' Clean up.
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try
End Function
To be honest - I cannot see how it can work. You are trying to use Excel spreadsheet as a database to store and retrieve data in real-time, for which Excel was never intended or designed.
You have mentioned that the Excel gets data several times per second. What is the source of data? RTD component? Bloomberg API? I would try to avoid the middle step of storing data in a spreadsheet.
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.