ASP.NET DropDownList posting "" - asp.net

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.

Related

ASP.NET - parametrize query for SqlDataSource in ASP.NET code behing- VB.NET / Visual Studio 2010

I am creating a query for a SqlDataSource in ASP.NET from code behind.
My code is as following:
Dim SqlDataSource1 As New SqlDataSource()
Dim SQL As String
' If Not IsPostBack Then
SqlDataSource1.ID = "sqlexpsearch"
Me.Page.Controls.Add(SqlDataSource1)
Dim connectionString As String
Dim connection As SqlConnection
connectionString = ConfigurationManager.ConnectionStrings("exam2ndconnection").ToString
connection = New SqlConnection(connectionString)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("exam2ndconnection").ConnectionString
If opname.Checked = True Then
SQL = "select SRNO,tr_date as Date ,MailMethod,SpeedId,Content,ExYear,Exroll as No,NAME,Address from dispatch where name = '%'+ #srname +'%' OR ADDRESS ='%'+ #srname +'%' order by TR_DAte DESC,NAME "
SqlDataSource1.SelectParameters.Add("#srname", UCase(txtitem.Text))
SqlDataSource1.SelectCommand = SQL
End If
If opchno.Checked Then
SqlDataSource1.SelectCommand = "select SRNO,tr_date as Date ,MailMethod,SpeedId,Content,ExYear,Exroll as No,NAME,Address from dispatch where rtrim(exroll) ='" & txtitem.Text & "' order by tr_Date,exroll desc"
End If
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
I get this error:
Must declare the scalar variable "#srname".
on the line of code:
Gridview1.DataBind()
Please help to resolve this problem.
I would avoid trying to inject (add) a sql datasource into a page. (they don't persist anyway - you would have to re-inject each time).
However, DO keep in mind that any data aware control ALWAYS will automatic persist for you anyway.
The above information is thus great, since then you don't even have to bother with the sql data source. This is especially so in your example - you want to fill out a dropdown list, a grid view - whatever. In those cases? Just shove into that control a datatable - and your off to the races.
As noted, a lot of us use + prefer using code in place of a data source on the page - I find them rather messy and a pain to work with anyway.
In fact, what I will often do is say drop in a listbox, or even a grid view. I then use the wizard to create new data source - lay out the grid real nice and fast. I then go into the markup, remove the data source conrol that appears in the page.
Also, don't forget to remove the DataSourceID = from the Gridview markup (or whatever control you using).
This lets me still use the wizards to create the gridview, listview etc. but then I delete that extra junk, and wind up with a nice clean page without all that extra stuff in the page - (which is a pain to control from code anyway).
So, say for your example?
Try coding it this way:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Using conn As New SqlConnection(ConnectionStrings("exam2ndconnection").ConnectionString)
Dim strSQL As String = ""
strSQL = "SELECT SRNO, tr_date as Date, MailMethod, SpeedId, Content, ExYear, Exroll as No, " &
"[Name], Address FROM dispatch "
Dim strWhere As String = ""
Using cmdSQL As New SqlCommand(strSQL, conn)
If opName.Checked Then
strWhere = "([Name] Like '%'+ #srname +'%' OR ADDRESS = '%'+ #srname +'%') "
cmdSQL.Parameters.Add("#srname", SqlDbType.NVarChar).Value = txtitem.Text
End If
If opchno.Checked Then
If strWhere <> "" Then strWhere &= " AND "
strWhere &= "(Rtrim(exroll) = #exroll)"
cmdSQL.Parameters.Add("#exroll", SqlDbType.NVarChar).Value = txtitem.Text
End If
If strWhere <> "" Then
cmdSQL.CommandText &= " WHERE " & strWhere
End If
' add our sorting
cmdSQL.CommandText &= " ORDER BY tr_Date, exroll DESC"
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rstData
GridView1.DataBind()
End Using
End Using
End Sub
A few things:
YES DO NOT forget to put the load of such data inside of the PostBack = false.
Load the results into a datatable (there are several reasons for this, but one BIG reason is that the row data bound event will have full use of that data row - including the WHOLE data row - even columns that are NOT part of the gridview.
note careful in above.
If you don't check "opname", then the criteria is not added.
if you don't check "opchno", then the criteria is not added.
if you check either one - the criteria for that option is added
so, if you check none, no criteria
if you check both, then you get both filters. So this allows you add even more options, and they are ALL optional - and we "clumative" can build up selection criteria this way.

Faster way to load drop down list

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...

webform multi column single row SQL Server result to vb variables

Ive looked through a few questions on here today and think I'm going round in circles.
My webform has a number of elements including username which is a drop down list (populated by a SQL statement)
On submit of the form i would like the code behind aspx.vb file run a select top 1 query and return a single row of data with 4 columns.
The returned SQL query result 4 columns would only be used later in the aspx.vb file so i want to assign each of the columns to a variable. I'm struggling with this task and assigning the variable the column result from the query.
Protected Sub submitbtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitbtn.Click
Dim connString1 As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString
Dim conn As New SqlConnection(connString1)
Dim sql1 As String = ""
Dim col1h As String = ""
Dim col2r As String = ""
Dim col3title As String = ""
Dim col4UQN As String = ""
sql1 = "SELECT TOP 1 col1h,col2r,col3title, col4UNQ from tblDistinctUserOHR where colID_Username= '" + username + "' "
Dim cmd1 As New SqlCommand(sql1, conn)
'open the connection
'run the sql
'the result will always be found but in case its not some form of safety catch (the variables stay as empty strings
'assign the results to the variables
'close connections
'lots of other code
End Sub
could someone point me in the right direction to run the SQL and assign the result to the the variables. I've been reading about ExecuteScalar() and SqlDataReader but that doesn't seem to be the correct option as the only examples I've found handle a single result or lots of rows with a single column
Thanks for any samples and pointers.
Try this:
Dim da As New OleDb.OleDbDataAdapter(sql1, conn)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count < 0 Then
col1h = dt.Rows(0).Item("col1h")
col2r = dt.Rows(0).Item("col2r")
col3title = dt.Rows(0).Item("col3title")
col4UQN = dt.Rows(0).Item("col4UQN")
Else
'No rows found
End If

Find nested gridview in user defined function

I'm having a problem populating a child gridview using a function I define. I keep getting the error "Object reference not set to an instance of an object". What am I doing wrong? Am I using the FindControl function incorrectly? It doesn't seem to find the child gridview.
Sub RecordsByZip()
Dim DBConn As New SqlConnection(Application("DBConn"))
Dim gv1 As GridView
gv1 = grdTotal
Dim gv2 As GridView
gv2 = DirectCast(gv1.FindControl("grdChild"), GridView)
Dim ZipCode = lbZip.SelectedItem
For Each ZipCode In lbZip.Items
If ZipCode.Selected = True Then
Dim cmdZip As SqlCommand = New SqlCommand("spPICAInsertTotals2", DBConn)
cmdZip.CommandType = CommandType.StoredProcedure
strZip = ZipCode.Text
strUser = Session("User")
Dim Zip As New SqlParameter("#Zip", SqlDbType.VarChar)
Zip.Value = strZip
cmdZip.Parameters.Add(Zip)
Dim UserID As New SqlParameter("#UserID", SqlDbType.Int)
UserID.Value = strUser
cmdZip.Parameters.Add(UserID)
DBConn.Open()
gv1.DataSource = cmdZip.ExecuteReader
gv1.DataBind()
gv1.Visible = True
DBConn.Close()
End If
Next
btnExport.Visible = True
lblmsg.Visible = False
' Dim DBConn = New SqlConnection(Application("DBConn"))
Dim cmdCounty As SqlCommand = New SqlCommand("spPICAInsertTotals", DBConn)
cmdCounty.CommandType = CommandType.StoredProcedure
'Dim gv As GridView = TryCast(e.Row.FindControl("grdChild"), GridView)
strUser = Session("User")
Dim UserID2 As New SqlParameter("#UserID", SqlDbType.Int)
UserID2.Value = strUser
cmdCounty.Parameters.Add(UserID2)
DBConn.Open()
gv2.DataSource = cmdCounty.ExecuteReader
gv2.DataBind()
gv2.Visible = True
DBConn.Close()
btnExport.Visible = True
lblmsg.Visible = False
lblInstructions.Visible = False
End Sub
First of all . . .
Just as a disclaimer, I normally use repeater controls instead of gridview controls.
But this may help you . . .
I can tell you that with repeater controls, if you want to find a nested repeater then you must look for them inside the item of the parent repeater to which they belong. Essentially, what you are trying to do with the code above, is find grdChild when there might actually be several grdChild (it is a nested gridview, after all). I'd be willing to bet this is where you're object reference error is occurring.
In other words, if you want to find the nested repeater with the ID nestedRepeater, and you know it is located in the first item of your main repeater (which in this case I've assigned to the myRepeater variable), you can do this:
Dim myItem as RepeaterItem = myRepeater.Items(0)
Dim Rep2 as Repeater = myItem.FindControl("nestedRepeater")
Using SqlDataAdapter and a DataSet (recommended)
Dim sa As New SqlDataAdapter(cmdCounty) 'Initialize the SqlDataAdapter and assign the SqlCommand object to it.
Dim ds As New DataSet() 'Initialize the DataSet (we will bind this to the gridview)
Try 'The Try/Catch statements help you to handle errors.
cmdCounty.Connection.Open() 'Open the connection to the database.
sa.Fill(ds) 'This statement uses the SqlDataAdapter to easily execute the SqlCommand (using the query specified in the SqlCommand object) and . . .
'. . .use that data to fill our dataset.
cmdCounty.Connection.Close() 'These statement close the connection and dispose of the SqlCommand object. Note: You may only need the dispose command.
cmdCounty.Dispose()
Catch ex As Exception
'Catch your error here.
cmdCounty.Connection.Close()
cmdCounty.Dispose()
End Try
gv2.DataSource = ds 'Set the datasource for your GridView control.
gv2.DataBind() 'Bind the data.
Using SqlDataReader and a DataTable
According to your comment, you're code is breaking when you assign the gridview to the cmd.ExecuteReader.
You will need to access your data using a method like this:
Dim rdr as SqlDataReader = cmdCounty.ExecuteReader() 'Declare the SqlDataReader and set it to handle your SqlCommand.
Dim dt as New DataTable 'Initialize a new DataTable. This is where we will place the information we read using the SqlDataReader.
'Make sure you add the columns...
dt.Columns.Add("firstColumnName") 'Create a column for each field you will be retrieving data from.
dt.Columns.Add("secondColumnName")
Dim r as DataRow 'Declare the variable r as a DataRow.
'You may want to insert the line "If rdr.HasRows Then" to check if any data was pulled before attempting to read it.
While rdr.Read() 'Loop through each row in the reader.
r = dt.NewRow() 'Set r to equal a new DataTable in the DataTable we created. Note: This does not actually add the row to the table.
r("firstColumnName") = rdr("firstColumnName") 'Set the values of each column in the current DataRow to equal their corresponding data read from SQL.
r("secondColumnName") = rdr("secondColumnName")
dt.Rows.Add(r) 'Add the DataRow r to the DataTable.
End While 'Loop back until there are no more rows.
gv2.DataSource = dt
gv2.DataBind()
Both of these examples assume you have already created your SqlCommand object and have assigned a working SQL query string and Connection object to it.

ASP.NET Button Click Event Issue (postback)

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.

Resources