displaying a table's field in a textbox - asp.net

I have a table and I want to select a field in it and then display it in a text box
something like:
SELECT userName
FROM userTable
WHERE (userLogged = 'ON')
how can I display the selected username in a textbox?
BTW the userLogged indicates wether the user is logged in or not
if the user is logged in then the userLogged will be changed to "ON"
if the user is not logged in it will be "OFF"
I know it's not that practical but I'm still practicing.
I'm using Visual Web Developer 2008 Express
--------- update ----------
I use table adapter procedures for querying

If you're just pulling a single field then the best way is to run your SqlCommand in scalar execution mode; which will return just one field/value.
Imports System.Data.SqlClient
....
Using sqlConn as new SqlConnection("Data Source=YourServer";Trusted_Connection=True;Database=DBName", _
sqlComm as new Sqlcommand("SELECT userName FROM userTable WHERE userLogged = 'ON'", sqlConn)
sqlConn.Open();
dim result as string = sqlComm.ExecuteScalar().ToString
TextBox1.Text = result
End Using
Note: "Trusted_Connection" inside the SQL connection string indicates to use windows authentication to login to the SQL Server; you can replace it with "User Id=Username; Password=Password;"

To set the text property on a textbox you simply call...
TextBox1.Text = "Value";
From your codebehind, If in your aspx page you have a textbox control...
<asp:TextBox ID="TextBox1" runat="server"/>
However there is much missing from your code example and many different ways of accessing a field value from a database

Well, this is a broad question as we don't know how you are querying the database or anything like that. Basically, you just take the result of your query, assuming it is in a DataTable object called dt and do something like this:
myTextBox.Text = dt.Rows[0]["userName"].ToString();
But, I suspect you need more than that. I recommend using the wonderful resources over at:
Learn Visual Studio.NET
It it a great place for beginners and has plenty of tutorials on ADO.NET.

Related

Stored Procedure from SQL Server is not filling ASP.Net dropdown using VB.Net coding

Situation:
I have a pre-built form that uses two Form Views. One is for pickup and one for delivery. The form can't be changed due to client requirements. The entire form and Form Views use a WizardStep process.
Each side pre-fills in the clients company name and related data such as Pickup Name, address, city, state etc as well as Delivery Info all using the same fields using the same stored procedure.
The stored procedure shows the concat of Name and Address 1 as FullName and the ClientSubCtr. ClientSubCtr is an int field. This id is what populates the correct data to each dropdown.
The dropdown list is not inside the FormView and falls under the form tag.
When testing the connection via the <asp:SqlDataSource> tag everything works in the Configure Data Source and data is returned using the appropriate parameter. The connection for the matching client data uses a basic Select to the table used in the stored procedure. I've tried to use a different stored procedure for the data, but no success there either. I am using SQL Server Express right now locally.
I've tried disabling the asp:SqlDataSource and just use a database connection from page_load, which did not work. I've commented it out as I'm still trying different things. I may be missing some syntax to connect to the dropdown here.
'This did not work
'Using conn As New SqlConnection(connect)
' strSQL = "SELECT ClientSubCtr,CONCAT(Name,Address1) AS FullName 'FROM tblClientsSub"
' strSQL = strSQL & " WHERE Account ='" & sessAccount & "'"
' strSQL = strSQL & " ORDER BY FullName ASC"
' conn.Open()
' Using cmd As New SqlCommand(strSQL, conn)
' cmd.Parameters.AddWithValue("#Account", sessAccount)
' cmd.CommandText = strSQL
' cmd.ExecuteNonQuery()
' Dim dr As SqlDataReader = cmd.ExecuteReader()
' If dr.HasRows Then
' Do While (dr.Read())
' ClientSubCtr = dr.GetValue(0)
' FullName = dr.GetValue(1)
' s1_cboAcct.DataTextField = FullName
' s1_cboAcct.DataValueField = ClientSubCtr
' s1_cboAcct.DataBind()
'Corrected Databind still does not work
' Loop
' Else
' dr.Close()
' End If
' End Using
'End Using
Additional info: Prior to using this I have two Pre-Render functions. One for Pickup and Delivery which fills in what my client calls a Docket. It shows the info that was pre-filled in with the initial loading or by the Selected Change on the dropdown and or where the client manually added or changed something, thus sending the correct information to the database for eventual download.
Note: This was originally written making OLEDB ACE connections to my clients Go Daddy account. Go Daddy moved the site to a new server and will no longer support ACE 12.0. We begged for them to change this. Thus, the move to SQL Server.
When I get what I believe is the data getting load I get an error in my pre-render on this tag. I've purposely commented out all the pre-render to see what was returned in regards to errors. No errors are return and the general form returns showing the drop-down but no data and the field in the FormView can't be seen. In other words not even the labels are showing. I've checked all asp:sqldatasource settings.
' If IsNothing("txtcboAcct.Text") Then
'lblDocketPUName.Text = ""
(I've tried using Request.form here, but data isn't loaded so I get nothing.) and commented out the If Else End If
' Else
' lblDocketPUName.Text = CType(frmViewPUClient.FindControl("txtcboAcct"), TextBox).Text
(This is where I get an error where the object is not found because neither the data for the dropdown is loading or the data for the forms.)
' End If
I know this is a lot to digest, but I'm totally baffled why this works perfectly using OLEDB and Access 2007 but when switching to SQL Server and the exact tables named the same, it does not. Any insight to why the stored procedure won't fill in the dropdown or why even my code in page_load wouldn't fill in the drop-down would be helpful. I've updated all parameters to use the # symbol.
Here is the stored procedure:
'ALTER PROCEDURE [dbo].[qryFullNameAddr]
'#Account nvarchar(10) OUTPUT
'AS
' -- Add the parameters for the stored procedure here
'DECLARE #ClientSubCtr int
'DECLARE #Name nvarchar(50)
'DECLARE #Address1 nvarchar(125)
'DECLARE #FullName nvarchar(255)
'BEGIN
' -- SET NOCOUNT ON added to prevent extra result sets from
' -- interfering with SELECT statements.
' SET NOCOUNT ON;
' /*Write statements for procedure here */
'SELECT ClientSubCtr,CONCAT(Name,Address1) AS FullName
'FROM tblClientsSub
'WHERE #Account=#Account
'ORDER BY FULLNAME, ADDRESS1 ASC
'end
Well, first I would back the truck up so to speak.
I would create a blank new test web page. Put in a dropdown list, and get it working.
Next up:
You don't need to loop for a drop down list. You can feed a dropdown a TABLE. And that table can be a query, or perhaps a stored procedure.
So, for starters, lets display a Hotel List in a drop down. And like most drop downs, there are often two columns the hidden "id" or often "PK" of the row, and then the display text.
So, our blank we page, we drop in a drop down list. Say like this:
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server"
DataTextField="HotelName"
DataValueField="ID" Height="22px" Width="219px">
</asp:DropDownList>
</div>
</form>
And now the code to fill - and as noted ALWAYS ALWAYS load only on first page load - that is PostBack = false - (break that rule, and you can't really even make a correctly working web page).
Ok, so our code is now this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData
End If
End Sub
Sub LoadData()
Using con As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "SELECT ID, HotelName from tblHotels ORDER BY HotelName"
Using cmdSQL As SqlCommand = New SqlCommand(strSQL, con)
con.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
DropDownList1.DataSource = rstData
DropDownList1.DataBind()
DropDownList1.Items.Insert(0, New ListItem("", "")) ' optional blank starting select
End Using
End Using
End Sub
That's it!!!
Also, don't know why so many code examples set the DataTextField and DataValue field in code? Why???? Just use the property sheet - little need to put such things in the code side - ESPECIALLY when the property sheet can do that for you!!!
Next up? Well, everyone always on SO piles in about how you should use parameters in such code in place of concatemer strings. This is correct, but if you code with parameters, then you can OFTEN reduce code, and CLEAN UP your sql anyway.
In place of say a messy sql string, you remove the text ('quotes'), and numbers (no quotes), and this even works better for dates.
So this benefit is near as great as the issue of sql injection issues.
(and to be fair, you noted a stored procedure, and it not working, so clearly you decided to try anything here - I get that approach).
So, your code snip? I would code it this way:
Dim strSQL As String =
"SELECT ClientSubCtr,CONCAT(Name, Address1) AS FullName FROM tblClientsSub " &
"WHERE Account = #Acc " &
"ORDER BY FullName ASC"
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, conn)
cmdSQL.Parameters.Add("#Acc", SqlDbType.NVarChar).Value = sessAccount
conn.Open()
s1_cboAcct.DataSource = cmdSQL.ExecuteReader
s1_cboAcct.DataBind()
End Using
End Using
Now is that not MUCH more readable?
And in fact cut + paste your code?
I noticed this:
SELECT ClientSubCtr,CONCAT(Name,Address1) AS FullName 'FROM
Wait? what is the ' right before the FROM???? You have a stray ', don't you?
Maybe that was a code cut + paste error, maybe not. But the REAL POINT?
By using parmaters we go nuclear on the single, double quotes, and all that jazz.
in other words, sure, avoiding string concntatiion of values is important for reasons of sql injection, but REALLY MUCH more valuable is how we don't have to bother with all those quotes and stuff. The result is it is MUCH HARDER to miss or mess up!!!
The other issue of course is by using the parameters as per above?
Well, we get intel-sense. And if I have several more, then in VS I just hit ctrl-d to dupplie the line. I actually wind up TYPING LESS code then If I attempted to introduce those values right into the sql!!! Imagine that - eaiser to read, and even less typing of code!!! - all this amounts up to much less error prone code. I mean, one missing quote like ' or a extra one? You in trouble and will waste time!!
You ALSO note that I did not even use a reader into a DataTable, and just shoved the reader results RIGHT into the combo box - saves even more code!!!!
However, while a dropdown, listview, gridview (and many more) can ALL accept DataSource as a cmdSQL.ExecuteReader as I did?
I still STRONG recommend you use my first version for Grids/list views etc. (and a HUGE reason exists for this!!!). (data pagers don't work if you feed a gridview a reader, but a table they work fine, and also the data bind events (not often used for combo box, but VERY often used for grids often needs the data source - so for this combo? Sure you can skimp out on the two extra lines of code (to create a DataTable and load it). But for a gridview, don't use that cool short cut I used above by feeding the reader directly into grids or listviews - but for combos, perfect fine.
So, with above, and after running above code, we have this:
As noted, if you DO test or decide to load up a combo box, and NOT use say a DataSoruce control dropped into the markup (I don't like those things all that much), then MAKE SURE you put and ONLY call the loading of such controls inside the If Not IsPostBack code stub. DO NOT EVER fail to follow this rule.
Again: do NOT EVER EVER fail to follow this rule.
Why?
Becuase any other button or any other thing you EVER will place on that page may well need to do a post-back (say even a few simple buttons). So, if you say select a combo box, fill out some other things, and have some button (and a button click event with code behind)?
Wel, keep in mind that page load ALWAYS FIRES each post-back!!!!
So, if your code re-loads say the combo box, then it going to blow out any existing selecting the user has for that combo (or grid or just about anything else!!!). So, you have to write your code in a way that it will "assume" and "work" and "survive" post-backs. So your loading up of controls thus should only be ONE time, and on the first page load - hence my HUGE LONG narrative of how vast important it is to follow this simple rule.

Add record on button click only

I have a form that has the 'data entry' property set to yes. It is bound to a table. When I start filling in the form it automatically saves it. I do not want this to happen. I only want the form to save to the table when I press a button. Any easy way to do this? w/o vba. If i can only do this with vba let me know how to do it that what.
The best way to do this is with an unbound form. When the user clicks save, you can run a query to update your table from the controls.
Using a recordset
Dim rs As Recordset
Set rs=CurrentDB.Openrecordset("MyTable")
rs.AddNew
rs!Field1 = Me.Field1
rs.Update
If you wanted to update a record where you already knew the primary key, you could say:
Dim rs As Recordset
Set rs=CurrentDB.Openrecordset("SELECT * FROM MyTable WHERE ID=" & Me.txtID)
rs.Edit
rs!Field1 = Me.Field1
rs.Update
Using a query that you have created in the query design window
SQL for the query
INSERT INTO MyTable (Field1)
VALUES ( Forms!MyForm!Field1 )
VBA
This will give a warning
DoCmd.OpenQuery "MyQuery"
This will not
CurrentDb.Execute "Query2", dbFailOnError
You could also use dynamic SQL or a query with parameters that you assign in code.

Making then displaying in a table a new SQL row using ASP

How can I, using asp.net and HTML, use a form to create a new table row in an SQL Table?
Would I use javascript to retrieve the HTML? Should I directly submit SQL or should I create a stored procedure? Essentially, I want to know how to get the data from a form to my SQL.
Take a look at the example provided in the documentation for the SqlCommand class.
In here they provide a basic example for connecting to a database, executing a query and processing the results. Here is a slightly modified version for doing an insert:
string queryString =
"INSERT INTO MyTable (Column1) Values ('test');";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
command.ExecuteNonQuery();
}
Make sure that you use a Parameterized Query when you use insert values from your web page into your database or you will be vulnerable to SQL Injection attacks.
There are several other methods for doing this such as LINQ-to-SQL, but feel this is the most straight forward for beginners.
Check out this for adding data: http://www.w3schools.com/ado/ado_add.asp
And check out this for updating data: http://www.w3schools.com/ado/ado_update.asp
You should use stored procedures to prevent security risks.
I strongly suggest you read:
ASP.NET Data Access to understand the basics, and then part 2 of step by step mySQL data access using ASP.NET

Using parameters to configure the table name in an SqlDataSource SelectCommand

I have an ASP.NET 3.5 web form with a DropDownList bound to a table of company names in a database. I also have a data bound GridView which I would like to update with data from the database depending on the company name selected in the DropDownList, so that the SelectCommand for the GridView's SqlDataSource is:
SELECT Registration, Telephone, Profile FROM {CompanyName}_VehicleData
Where {CompanyName} is whatever is selected in the DropDownList. I've used the Command and Parameter Editor to create a ControlParameter pointing to the SelectedValue of the DropDownList, but I don't know how to write the SelectCommand query to concatenate the parameter to '_VehicleData'. Any thoughts.
If you are using a sqldatasource you could set the select command in the code behind.
<sqldatasource>.SelectCommand = "select registration, telephone, profile " & _
"from " & <dropdown>.selectedvalue & "_VehicleData"
<sqldatasource>.SelectType = SqlDataSourceCommandType.Text
#Colin: You said that the solution is writing a stored procedure that evaluates whether the concatenated value (DropDown.SelectedValue + "_VehicleData") maps to a real table using the INFORMATION_SCHEMA.TABLES view before injecting it into a SQL command. Can you please give a code snippet for the stored proc?

asp.net sqlcommand not doing as it should - debugging help req

This is a really odd situation that I can't seem to work out where the problem lies.
I have a simple ASP textbox and button, on clicking the button I have a simple sqlconnection/command routine perform a simple update to a database based on the text value of the textbox.
Code:
Using myConnection As SqlConnection = New sqlConnection(ConfigurationManager.ConnectionStrings("sqldbconn").ConnectionString)
myConnection.Open()
Dim strSQL As String = "insert into users(name) select #name"
Dim myCommand As New Data.SqlClient.SqlCommand(strSQL, myConnection)
myCommand.CommandType = Data.CommandType.Text
myCommand.Parameters.Add(create_Parameter("#name", Data.SqlDbType.VarChar, 50, Data.ParameterDirection.Input, txName.Text))
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
create_Parameter is just a simple tested function which performs the 2-3 lines it normally takes to create a parameter object.
The problem I have, is that the value added to the database is always a comma, followed by the text given in the textbox.
I have performed response.write's prior to the ExecuteNonQuery call to check both the Parameter value and the CommandText, which are fine and as expected. If I copy what's expected into a management studio query window, it works fine.. users is a simple table with varchar column, no triggers or constraints etc. There are no other sub's in the ASP code other than what I've shown.
So now I'm stuck, what else can I do to work out where/why this comma is being added to my insert statement???
Cheers!
Probably nothing to do with your issue, but I wold normally write an insert like this:
INSERT INTO users (name)
VALUES #name

Resources