I have searched for what I think is a simple solution.
In my aspx.vb code page, I need to make a connection to SQL Server (my connection strings are in the web.config file) and then make a simple SQL Select to return one or 2 values.
For example, the user will select a customer on the ASP form, then I need to read a couple of default values from that user's record and display them back onto the form.
Can someone provide the sample code or direct me to this? I'm thinking that this is rather simple, but I can't seem to make it work. If I see a sample of exactly what I need to do, such as reading a value using the Northwind sample DB, then I can modify it to fit my table structure, etc.
Thank you.
Hi,
Here is a sample code that you can run on a web form which reads an Id value from a textbox and then returns the firstname and lastname of the customer.
PrivateSub Button5_Click(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Handles Button5.ClickDim sqlConnectionStringAsString = System.Configuration.ConfigurationSettings.AppSettings.Get("ConnectionString")Dim sqlConnectionAs SqlClient.SqlConnection =New SqlClient.SqlConnection(sqlConnectionString)Dim sqlCommandAs SqlClient.SqlCommand =New SqlClient.SqlCommand("SELECT FirstName, LastName FROM Customers Where CustomerId = @.CustomerId")Dim sqlParamAs SqlClient.SqlParameter =New SqlClient.SqlParameter("@.CustomerId",CInt(txtCustomerId.Text))sqlCommand.Parameters.Add(sqlParam)
sqlCommand.Connection = sqlConnection
sqlConnection.Open()
Dim drAs SqlClient.SqlDataReaderdr = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection)
While dr.ReadtxtFirstName.Text =
CType(dr.GetValue(dr.GetOrdinal("FirstName")),String)txtLastName.Text =
CType(dr.GetValue(dr.GetOrdinal("LastName")),String)EndWhiledr.Close()
EndSub
You can use the below line of code to get the connection string from the web.config file
System.Configuration.ConfigurationSettings.AppSettings.Get("ConnectionString")
You should have placed the below configuration declaration within the configuration tags (<configuration></configuration>)
<appSettings><addkey="ConnectionString"value="..."/></appSettings>
Eralper
http://www.kodyaz.com
|||
How come my intellisense does not automatically pop-up the wording 'SqlClient...' in my dim statements. Nothing seems to be wrong with my set up as I have been working fine for months, but now that I am trying to ad-hoc querries I don't have access to these facilities..
Dim sqlConnectionAsSqlClient.SqlConnection =New SqlClient.SqlConnection(sqlConnectionString)Dim sqlCommandAsSqlClient.SqlCommand =New SqlClient.SqlCommand("SELECT FirstName, LastName FROM Customers Where CustomerId = @.CustomerId")Dim sqlParamAsSqlClient.SqlParameter =New SqlClient.SqlParameter("@.CustomerId",CInt(txtCustomerId.Text))
|||
Never mind, I just had to add
Imports System.Data
Imports System.Data.SqlClient
No comments:
Post a Comment