Multiple Values in DropdownList.DataTextField Not Working - asp.net

I have the below code which is populating a dropdownlist in ASP.NET. When I use a single value, everything works like a charm, but I want the DataTextField to use two fields coming from the database, not one. Any assistance would be greatly appreciated. I have tried several ways, but nothing seems to work :(
Dim connstr As String = Session("ConnStrEP")
Using con As New SqlConnection(connstr)
Using cmd As New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "GetWaivers"
cmd.Connection = con
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
dr.Read()
Code.DataSource = dr
Code.DataTextField = String.Format("{0}, {1}", Code.SelectedValue("tblWVCode").ToString(), Code.SelectedValue("tblWVDesc").ToString())
Code.DataValueField = "tblWVDesc"
Code.DataBind()
dr.Close()
con.Close()
End Using
End Using
UPDATE:
I generated the below SQL, but I am receiving an error when I execute the SQL Server 2008 Stored Procedure. "Invalid operator for data type. Operator equals add, type equals ntext.
"
SELECT TblWvCode, TblWvDesc, (TblWvCode + ' - ' + TblWvDesc) As FullList FROM EP.dbo.WaiverVarianceTbl

Modify the stored proc to concatenate the tblWVCode and tblWVDesc values and return them in a new field, you can then use that field for the DataTextField

You can't do that, you'll need to change your SQL query to return the field on the format you need. DataTextField must be a field or property name.
Your query should looks like this
SELECT
TblWvCode,
TblWvDesc,
(
CAST(TblWvCode as nvarchar(max)) + ', ' + CAST(tblWVDesc as nvarchar(max))
) as FullList
FROM EP.dbo.WaiverVarianceTbl
and then your VB code would be something like this
Code.DataTextField = "FullList"
Code.DataValueField = "tblWVDesc"

Related

Execute Scalar to Label. Subquery returned more than 1 value

So I have a label which shows the username of the user. I've used this value to return their ID which I then attach to a label. I used execute scalar to do this because I wasn't sure how else to get a single value on a label.
This works fine. I then use the ID from the label and put it in another table. I can do this twice and then the page crashes saying...
"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
However I don't understand. I don't pull anything from the second table on the page. I don't know why it would affect it. I feel like I've tried everything. Taking out the line that posts the ID to the label lets the page run but I need it there.
Label2.Text = User.Identity.Name
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
connetionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True"
sql = "SELECT SupID FROM Supervisor WHERE (Email = #Email)"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(sql, cnn)
cmd.Parameters.Add(New SqlParameter("#Email", User.Identity.Name))
Dim supid1 As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
cnn.Close()
Label1.Text = supid1.ToString
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
This should return the first result for you. Also, it's a good idea to employ Using blocks for objects such as connections, commands, and readers.
Using cn = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True")
cn.Open()
Using cmd = New SqlCommand("SELECT SupID FROM Supervisor WHERE Email = #Email", cn)
cmd.Parameters.AddWithValue("#Email", User.Identity.Name)
Using dr = cmd.ExecuteReader
If dr.Read Then
Label1.Text = CInt(dr("SupID"))
End If
End Using
End Using
End Using
If you are not sure there are multiple rows for same email in that table, you can change the query to following, that will work for you with executescalar.
SELECT TOP 1 SupID FROM Supervisor WHERE (Email = #Email)
Horribly sorry! But yes you were right! There was another query going on in the background that I never noticed that was affecting it all. So sorry

SQLClient output parameter returns DBNull

Its a ASP.net application in VS2008, connecting to SQL 2005 database.
No errors calling the Stored procedure, db update is successful but the OUTPUT param returns DBnull all the time. Below the vb code:
Dim ConnectString As String = "", connect As New Data.SqlClient.SqlConnection
ConnectString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connect.ConnectionString = ConnectString
Dim cmd As New SqlCommand("saveAccess", connect)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter("#Name", "SampleName"))
Dim outparam As SqlParameter = New SqlParameter("#returnValue", SqlDbType.Int)
outparam.Direction = ParameterDirection.Output
cmd.Parameters.Add(outparam)
connect.Open()
cmd.ExecuteNonQuery()
If IsDBNull(cmd.Parameters("#returnValue").Value Then
Response.Write("Why does it always returns DBNull")
Else : Response.Write(cmd.Parameters("#returnValue").Value.ToString())
End If
connect.Close()
Here is the SQL code
ALTER PROCEDURE [dbo].[saveAccess]
(#Name NVARCHAR(20), #returnValue INT OUTPUT )
AS
BEGIN
INSERT INTO Access ([Name]) VALUES (#Name);
SELECT #returnValue = ##ROWCOUNT;
END
Not sure what is the silly mistake that I am doing. Any input helps.
Thanks
Instead of SELECT, try using SET to set the value of the output parameter
SET #returnValue = ##ROWCOUNT;
Solution (as said silly myself): missed the # symbol in front of the returnValue variable. I typed up the code in this posting correctly but I had it without the # in the SP.
wrong: SELECT returnValue = ##ROWCOUNT;
correct: SELECT #returnValue = ##ROWCOUNT;
Thanks

VB.NET ORA-01745: invalid host/bind variable name

For the last 2 hours I was trying figure out why the parameter could not be bound (Well I know I was not using the "using" block. And I know System.Data.OracleClient is deprecated.) Please help me see what's wrong with the following code:
Dim nCount As Integer
sSQL = " SELECT COUNT(*) FROM USERS WHERE USER_ID = :UID "
Dim conn As OracleConnection = New OracleConnection(ConfigurationSettings.AppSettings("connString"))
conn.Open()
Dim cmd As OracleCommand = New OracleCommand(sSQL, conn)
cmd.CommandType = CommandType.Text
With cmd
.Parameters.Add(New OracleParameter(":UID", txtUserID.Text))
End With
Try
nCount = cmd.ExecuteScalar()
Catch ex As Exception
End Try
I have tried all variations I can find online: with or without colon in the Parameters.Add, Add or AddWithValue, Add in a parenthesis or create a new OracleParameter object then add it...Nothing seems to work.
But if I just hard-code the USER_ID in the query, remove the parameter.Add, it would return a value.
A HA!
UID is actually a reserved word in Oracle. Change your UID variable to something that is not a reserved word.
For me it seems that you missed something, while experimenting with different combinations.
This variant must work:
Dim nCount As Integer
sSQL = "SELECT COUNT(*) FROM USERS WHERE USER_ID = :UID"
Dim conn As OracleConnection = New OracleConnection(ConfigurationSettings.AppSettings("connString"))
conn.Open()
Dim cmd As OracleCommand = New OracleCommand(sSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("UID", OracleType.VarChar).Value = txtUserID.Text
nCount = cmd.ExecuteScalar()
Please try it ...
Do yourself a favor and at least look into ODP from Oracle. You'll need it with Microsoft finally pulls the plus on its OracleClient. The switch over to ODP is very easy.
In your situation, I'd leave off the parameter name. You're binding by position anyway.
The SQL syntax is also a little different in the Microsoft implementation. Use a ? to act as each placeholder. See http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracleparameter.aspx for further information.

Not getting the correct results of an SQL query to be displayed in a grid view

I have a query which only retrieves the records of the Description Field of Table 1 that do not match or contain the keywords available in the Keywords Field in Table 2. So the ones that match should not appear in the GridView, rather only the ones that do not match. I am trying to display the results of the SQL Query in a GridView, however I am getting the ones that match, which is not my requirement.
I tried running the SQL Query in SQL Server and it works really fine. Even in my web app it works fine, but only if I specify explicitly the keyword after the Like Statement. But rather I want it to span all the Keywords in Table2. Here is my code.
conn.Open()
For Each row As GridViewRow In Me.GridView1.Rows
For i As Integer = 0 To GridView2.Rows.Count - 1
Dim Records1 As String = GridView2.Rows(i).Cells(0).Text
Dim cmd = New SqlCommand("Select DISTINCT Description From DB.dbo.Table1 " +
"WHERE NOT EXISTS (Select * From [DB].dbo.Table2 WHERE " +
"Table1.Description LIKE '%' +TABLE2.Keywords + '%')", conn)
DA.SelectCommand = cmd
DA.Fill(dt)
GridView3.DataSource = dt
GridView3.DataBind()
cmd.ExecuteNonQuery()
cmd.Dispose()
DA.Dispose()
dt.Clear()
dt.Dispose()
Next
Next
GridView1 has the data from Table1 (The Description)
GridView2 has the data from Tabel2 (The Keywords)
GridView3 has the results of the query
However, as said before I am still getting the ones that match. Is there something wrong with the format of the query, something missing or written in an incorrect format? Any suggestions or thoughts would really be appreciated.
shouldn't that be:
WHERE Table1.Description LIKE #Grid)"
cmd.Parameters.AddWithValue("#Grid", "%" + GridView2.Rows(i).Cells(0).Text.ToString() + "%")
Better solution would be to do this from within a stored procedure and pass the #Grid parameter. IMHO
But, to answer your question specifically, this should work
For i As Integer = 0 To GridView2.Rows.Count - 1
Dim Records1 As String = GridView2.Rows(i).Cells(0).Text
Dim cmd = New SqlCommand("Select DISTINCT Description From DB.dbo.Table1 " +
"WHERE NOT EXISTS (Select * From [DB].dbo.Table2 WHERE " +
"Table1.Description LIKE "
"'%" + GridView2.Rows(i).Cells(0).Text.ToString() + "%')", conn)
DA.SelectCommand = cmd
DA.Fill(dt)
GridView3.DataSource = dt
GridView3.DataBind()
cmd.ExecuteNonQuery()
cmd.Dispose()
DA.Dispose()
dt.Clear()
dt.Dispose()
Next

Getting row Count only returns value of 1

I am using Sql Server 2005 and Vb Studios 2010 on a .net Framework of 4.0. I am trying to get the exact number of rows from a database and populate a datatable then have a label show the number of rows.
Dim comm2 = db.selectcommand(db.conn, "*", "Tablename", " columnname = '" & Session(sessionvariable) & "' AND columnname = 'Unread '")
Dim sqlda2 As New SqlDataAdapter(comm2)
Dim dt2 As New DataTable
sqlda2.Fill(dt2)
Dim recordcount As Integer = dt2.Rows.Count
messagecountlbl.Text = recordcount
this will always return the value of 1 and I know for a fact that I have multiple values for the data I am trying to pull. I have atleast 50 and the label should be displaying that amount.
I have also tried the Select Count statement and it does the same thing.
Fix I have added this to the post since there is a 24 hr wait to answer question:
I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult
Aren't you missing quotes around Unread?
Also... you're susceptible to SQL Injection. Use Parameters instead
Also... if all you are doing is getting the number of rows, your code is overkill
I just noticed.... you Dimmed comm2 but your adapter uses comm
Your updated question was the route that I would have gone. This was why i said your initial code was overkill (in terms of memory usage...). DataAdapters and DataTables for one value is in no way efficient.
You might want to change your updated code to the following...
Again, look up SQL Injection to see why you should never (or at least try not to) build a sql string like that
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = #param"
sql.Parameters.AddWithValue("#param", Session("sessionvariable"))
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult
It looks like you're missing a single quote at the beginning of the word "Unread".
...& "' AND columnname = 'Unread'")
I note that your first line declares a variable called comm2 but you don't use it later - instead you're using simply comm.
With that in mind, the fact that you've omitted the quotes around Unread will still be relevant.
Fix I have added this to the post since there is a 24 hr wait to answer question: I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult

Resources