I have three dropdownlist which values are to be inserted in one particular field in the database. But i am new to ASP.
This are my following codes:
Dim strConn = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim myConn As New SqlConnection(strConn)
Dim cmd = "INSERT INTO [IndividualWorkout] (WorkoutProgramName, WorkoutProgramPosted, WorkoutProgramDesc, IndividualWorkoutName, IndividualWorkoutTips, TimingID) VALUES (#WorkoutProgramName, #WorkoutProgramPosted, #WorkoutProgramDesc, #IndividualWorkoutName, #IndividualWorkoutTips, #TimingID)"
Dim myCmd As New SqlCommand(cmd, myConn)
myCmd.Parameters.AddWithValue("#WorkoutProgramName", TextBox1.Text)
myCmd.Parameters.AddWithValue("#WorkoutProgramPosted", TextBox2.Text)
myCmd.Parameters.AddWithValue("#WorkoutProgramDesc", TextBox3.Text)
myCmd.Parameters.AddWithValue("#IndividualWorkoutName", TextBox4.Text)
myCmd.Parameters.AddWithValue("#IndividualWorkoutTips", TextBox5.Text)
myCmd.Parameters.AddWithValue("#TimingID", DropDownList4.SelectedValue.ToString())
myCmd.Connection = myConn
myConn.Open()
myCmd.ExecuteNonQuery()
myConn.Close()
Could anyone guide me/help me with the editing of the following code so that the 3 dropdownlist values which were selected will go in the TimingID.
Thanks
If you want to concatenate the values, you can do it like this.
string s = DropDownList4.SelectedValue.ToString() + "|"
+ DropDownList5.SelectedValue.ToString() + "|"
+ DropDownList6.SelectedValue.ToString();
myCmd.Parameters.AddWithValue("#TimingID", s);
Then you will have to parse out the 3 values when you retrieve the data from that field with a .Split() or similar function.
Just as a note, it seems odd to have an ID field use concatenated strings. I'm assuming this field requires uniqueness, which seems at risk by using a combination of dropdown values. Do you have that covered?
Related
I have a dropdownList with control ID of HourlyCharter.
Then on codebehind, I am trying to query records from the database where hourly is equal to the value of HourlyCharter.
If I use this code:
StrSQL = "select h.fare, h.tip, h.total from hourlyQRY h "
StrSQL += " Where h.Hourly = " & HourlyCharter.SelectedValue
' Initialize Database Connection
Dim connStr As String = ConfigurationManager.ConnectionStrings("ALSConnectionString").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(StrSQL, conn)
It works.
If I use parameterized query such as this:
StrSQL = "select h.fare, h.tip, h.total from hourlyQRY h "
StrSQL += " Where h.Hourly = #hourly"
' Initialize Database Connection
Dim connStr As String = ConfigurationManager.ConnectionStrings("ALSConnectionString").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(StrSQL, conn)
'We use parametized query to prevent sql injection attack
Dim p1 As New OleDbParameter("#hourly", HourlyCharter.SelectedValue)
cmd.Parameters.Add(p1)
I get following error:
Data type mismatch in criteria expression
Hourly is of Number data type and we are using Access 2010 database.
Any ideas how to resolve this?
'open recordset to receive db values
rs = cmd.ExecuteReader()
' This acts like the (Not RecordSource.Eof) in ASP 3.0 to loop and retrieve records.
While rs.Read()
' If rs("city") <> "" Then
Dim tipValue As Decimal = rs("tip")
Dim totValue = rs("total")
' Else
' End If
Dim tp As String = [String].Format("{0:C}", tipValue)
Dim tot As String = [String].Format("{0:C}", totValue)
lblTip.Text = tp
lblTotal.Text = tot
End While
You need to make sure the object you put in the parameter is also a numeric type. SelectedValue is a string.
Dim p1 As New OleDbParameter("#hourly", Decimal.Parse(HourlyCharter.SelectedValue))
That's where the data type mismatch happens - it's expecting a number but it's getting a string.
Instead of
Dim p1 As New OleDbParameter("#hourly", HourlyCharter.SelectedValue)
cmd.Parameters.Add(p1)
You can try
cmd.Parameters.AddWithValue("#hourly", HourlyCharter.SelectedValue)
Try specifying the datat type of the parameter. You can do it after creating it:
p1.OleDbType = OleDb.OleDbType.Numeric
You can also do it on the constructor, but it requires a lot more parameters and I'm not sure you have all those nor I do know what they do.
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"
I am new to asp.net and here I am trying to populate a single text box with a value from database.
I have created this code but not working:
Try
Dim MyCon As New SqlConnection("server = servername; uid = sa; pwd =abc; database = master")
Dim MyCommand As New SqlCommand("Select empFirstName from Employees where empid=2")
MyCon.Open()
Dim MyReader = MyCommand.ExecuteReader()
While MyReader.Read()
Dim sqlda = New SqlDataAdapter()
Dim dt As New Data.DataTable()
Dim ds As New Data.DataSet
sqlda.Fill(ds)
TextBox1.Text = ds.Tables(0).ToString
MyCon.Close()
End While
Please correct the code and tell me where I am wrong.
Kindly suggest me a link if any to read more on this topic for beginners with example.
Try this sample, it will work for you http://geekswithblogs.net/dotNETvinz/archive/2008/09/12/bind-textbox-and-label-control-with-data-from-database.aspx
ds.Tables(0)
will return a DataTable
If you want to get the tablename, write this instead:
ds.Tables(0).TableName
If you want to get value returned, write this kind of code:
ds.Tables(0).Rows(0).Item("empFirstName")
This will store only the 1st row from the database
TextBox1.Text = ds.Tables(0).Rows(0)(0).ToString();
Row(0)(0) indicates to get the 1st row from the 1st column
If the query is returning more than 1 rows then u need to iterate the data table and store it in a List(Of String) instead of an array as you don't know the number of rows returned from the query
Dim EmpFirstName As New List(Of String)
Dim myRow As DataRow
Dim myColumn As DataColumn
For Each myRow in dt.Rows
EmpFirstName.Add(myRow(dt.Columns(0)))
Next
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
I have a textbox and a button on a form.
I wish to run a query (in Vb.Net) that will produce a query with the IN Values.
Below is an example of my code
myConnection = New SqlConnection("Data Source=sqldb\;Initial Catalog=Rec;Integrated Security=True")
myConnection.Open()
myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 where RecID in ('" & txtRecID.Text & "') ", myConnection)
ra = myCommand.ExecuteNonQuery()
myConnection.Close()
MsgBox("Done!", _
MsgBoxStyle.Information, "Done")
When I enter a single value it works but when I enter values with commas it throws an error:
"Conversion failed when converting the varchar value '1234,4567' to
data type int."
Could someone please help me to solve this or if there is an alternative way?
Many Thanks
Try removing the single-quotes you're wrapping the IN values in:
myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 WHERE RecID IN (" & txtRecID.Text & ") ", myConnection)
If you were testing a STRING variable for multiple values, then those multiple values would need to be in quotes.
The reason your first attempt 'almost' worked was because you could also have generated your SqlCommand with each individual value in quotes.
I.E.
UPDATE dbo.Recordings SET Status = 0 where RecID IN ('1234', '5678')
In that case, T-SQL would have done an implicit conversion of each of the string values to INT,
which is what it was attempting to do when you gave it '1234, 5678' but that isn't decipherable as an INT.