Change SqlDataSource ConnectionStrings value in code behind (vb.net) - asp.net

I currently have this code in the front of my ASP.NET page
<asp:SqlDataSource ID="SqlDataSourceRecentJobs" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString_DEV_customer_support %>"
ProviderName="<%$ ConnectionStrings:ConnectionString_DEV_customer_support.ProviderName %>"
SelectCommand="SELECT job_id FROM time_recorder_jobs WHERE (deleted = 0) ORDER BY job_id DESC LIMIT 1">
</asp:SqlDataSource>
Which works fine.
However, I want to set or define the value of 'ConnectionStrings' using the codebehind - based on a session variable.
My web.config contains:
<connectionStrings>
<add name="ConnectionString_DEV_customer_support" connectionString="server=REMOVED;port=REMOVED;User Id=REMOVED;password=REMOVED;Persist Security Info=True;database=dev_customer_support;Sql Server Mode=True;Allow User Variables=True" providerName="MySql.Data.MySqlClient" />
<add name="ConnectionString_LIVE_customer_support" connectionString="server=REMOVED;port=REMOVED;User Id=REMOVED;password=REMOVED;Persist Security Info=True;database=customer_support;Sql Server Mode=True;Allow User Variables=True" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
So I wish to set either ConnectionString_DEV_customer_support or ConnectionString_LIVE_customer_support in the code behind, depending on which server environment the user is on.
I thought something like this would work (but it does not):
Dim SqlDataSourceRecentJobs As New SqlDataSource()
If Session("Environment") = "LIVE" Then
strUseThisDB = "ConnectionString_LIVE_customer_support"
Else
strUseThisDB = "ConnectionString_DEV_customer_support"
End If
SqlDataSourceRecentJobs.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings(strUseThisDB).ConnectionString
Using the code behind (I use VB, not C#), how do I set/define/specify which of my ConnectionStrings I want to use?
Just to add, if it makes a difference, I also want to set the SELECT in the code behind too.
Eg.
SqlDataSourceRecentJobs.SelectCommand = "SELECT time_recorder_jobs.job_id, time_recorder_jobs.user_id, time_recorder_jobs.operation_id, time_recorder_jobs.task_id, time_recorder_jobs.customer_id, time_recorder_jobs.farm_id, time_recorder_jobs.output, time_recorder_jobs.start_time, time_recorder_jobs.end_time, time_recorder_jobs.comments FROM time_recorder_jobs INNER JOIN time_recorder_users ON time_recorder_jobs.user_id = time_recorder_users.user_id INNER JOIN time_recorder_companies ON time_recorder_users.company_id = time_recorder_companies.company_id WHERE (time_recorder_jobs.deleted = #deleted) AND (time_recorder_users.company_id = #companyid) ORDER BY time_recorder_jobs.job_id DESC LIMIT 10"
SqlDataSourceRecentJobs.SelectParameters.Clear()
SqlDataSourceRecentJobs.SelectParameters.Add("#companyid", Session("CompanyID"))
SqlDataSourceRecentJobs.SelectParameters.Add("#deleted", 0)

You could do something like this:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
SqlDataSourceRecentJobs = New SqlDataSource
conn = New MySqlConnection
If ConfigurationManager.ConnectionStrings("ConnectionString_DEV_customer_support").ConnectionString Is Nothing OrElse _
ConfigurationManager.ConnectionStrings("ConnectionString_DEV_customer_support").ConnectionString.Trim() = "" Then
Throw New Exception("Connection Error")
Else
conn.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString_DEV_customer_support").ConnectionString
End If
SqlDataSourceRecentJobs.ConnectionString = conn.ConnectionString
SqlDataSourceRecentJobs.ID = "SqlDataSourceRecentJobs"
SqlDataSourceRecentJobs.ProviderName = "MySql.Data.MySqlClient"
SqlDataSourceRecentJobs.SelectCommand = "SELECT * FROM time_recoder_jobs"
SqlDataSourceRecentJobs.CancelSelectOnNullParameter = False
Me.Controls.Add(SqlDataSourceRecentJobs)
End Sub
I use the Page_Init to load the DataSource

Related

VB.NET Connection string ADODB Connection (Web.Config)

I write the code below to connect database using web config but cannot connect database using ADODB to fetch data from database into textboxes
Webconfig
<connectionStrings>
<clear />
<add name="constr" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|CustomerInfor.mdb" providerName="System.Data.OleDb"/>
</connectionStrings>
SearchButton
Dim consString As String = System.Configuration.ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim objConn As New OleDbConnection(consString)
objConn.Open()
Please help with right code to fetch data from database into textboxes
Thanks
Ok, lets try this a bit different.
First up: Lets get the connection string OUT side of the code.
Like for desktop, or anything else? You can add values like connection string to the project like this:
And really nice is you get to use the connection builder to do this.
The above setting are shoved into web.config for you automatic.
So, setup your connection in above.
Ok, now in this case, I just shove on the screen a few text boxes for a user and hotel name.
Real plane jane like this:
<div style="width:25%;text-align:right;padding:25px;border:solid;border-width:1px">
<style> .tbox {width:260px;margin-left:5px;margin-bottom:15px;border-radius:8px;border-width:1px}</style>
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" class="tbox"/>
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" class="tbox" />
<br />
Last Name:<asp:TextBox ID="txtLast" runat="server" class="tbox"/>
<br />
City: <asp:TextBox ID="txtCity" runat="server" class="tbox"/>
<br />
Active:<asp:CheckBox ID="ckActive" runat="server" />
<br />
<br />
Ok, now our code to load this. I don't have a text box or source for the id, but a integer value OR a text value will work.
So, our code to load up is 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()
Dim cmdSQL As OleDbCommand = New OleDbCommand()
cmdSQL.CommandText = "SELECT * from tblhotels where ID = #ID"
cmdSQL.Parameters.Add("#ID", OleDbType.Integer).Value = 23
Dim rst As DataTable = MyRst(cmdSQL)
With rst.Rows(0)
txtHotelName.Text = .Item("HotelName")
txtFirst.Text = .Item("FirstName")
txtLast.Text = .Item("LastName")
txtCity.Text = .Item("City")
ckActive.Checked = .Item("Active")
End With
ViewState("rst") = rst
End Sub
Note the cute helper routine MyRst.
So, you can use that routine EVERY where. eg:
Dim cmdSQL As OleDbCommand = New OleDbCommand("select * from RoomTypes")
Dim rst as DataTable = MyRst(cmdSQL)
So, it just a handy dandy routine. (you do NOT have to use parameters if you don't need them).
Ok, so we loaded the one row into the table (and we save that row for later use into ViewState)
Ok, so now we see this:
Now, the save code. Note how we used a record set (datatable) in place of a GAZILLION parameters.
We do this for quite a few reasons.
Strong data type conversion occurs here.
Parameter order for the save does not matter. I can cut-paste, or add 5 or 15 more columns here, and it works - and order does not matter!!!
So, now the save code.
Protected Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
SaveData()
End Sub
Sub SaveData()
Dim rst As DataTable = ViewState("rst")
Using con As New OleDbConnection(My.Settings.AccessTest2)
Using cmdSQL As New OleDbCommand("SELECT * from tblHotels WHERE ID = 0", con)
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmdSQL)
Dim daSQLU As OleDbCommandBuilder = New OleDbCommandBuilder(da)
con.Open()
With rst.Rows(0)
.Item("HotelName") = txtHotelName.Text
.Item("FirstName") = txtFirst.Text
.Item("LastName") = txtLast.Text
.Item("City") = txtCity.Text
.Item("Active") = ckActive.Checked
End With
da.Update(rst)
End Using
End Using
End Sub
NOTE: not a bug, I MOST certainly did use where ID = 0
So, the nice part is we can add more text box etc. We will have to add code to setup the text boxes, but at least the order don't matter.
Last but not least?
That helper routine, the one I use to fill datatables. I even use it for say filling out combo box (dropdown lists), or whatever.
Public Function MyRst(cmdSQL As OleDbCommand) As DataTable
Dim rstData As New DataTable
Using MyCon As New OleDbConnection(My.Settings.AccessTest2)
cmdSQL.Connection = MyCon
MyCon.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
Return rstData
End Function
So note how we used the connection string setting that we setup in the project.
And since access is sensitive to parameter order, then I adopted the above idea of using a data table. Note that this approach also works for a grid, or even adding rows. When you run that update routine? rows added, rows edits, row deleted?
They all are done for you with the ONE da.Upate(rst).
Note also, you should set your project to run as x86, and not x64, since JET ONLY can work as x32. However, the ACE data engine can be had for x64 bits.

unable to retrieve the role in asp.net with MSSQL Server

I am working with asp.net and MSSQL server for development of online application, I like to add roles and Membership in website, membership and roles are stored in SQL Server, I tried and successes for login with SQL Users and while i change the code for restricted access for specific role the role is not listing on page.
my code for page are like below:
For Login
Dim userId As Integer = 0
Dim roles As String = String.Empty
Dim constr As String = ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("Validate_User")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Username", Username.Text)
cmd.Parameters.AddWithValue("#Password", Password.Text)
cmd.Connection = con
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
reader.Read()
userId = Convert.ToInt32(reader("UserId"))
roles = reader("Roles").ToString()
con.Close()
End Using
con.Close()
End Using
Select Case userId
Case -1
errorText.Visible = True
errorText.Text = "Username and/or password is incorrect."
Exit Select
Case Else
Dim ticket As New FormsAuthenticationTicket(1, Username.Text, DateTime.Now, DateTime.Now.AddMinutes(1), True, roles,
FormsAuthentication.FormsCookiePath)
Dim hash As String = FormsAuthentication.Encrypt(ticket)
Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, hash)
If ticket.IsPersistent Then
cookie.Expires = ticket.Expiration
End If
Response.Cookies.Add(cookie)
Session("login") = Username.Text
Response.Redirect(FormsAuthentication.GetRedirectUrl(Username.Text, True))
Exit Select
End Select
After that Master Page for Code :
Page Load
If Not Me.Page.User.Identity.IsAuthenticated Then
Response.Redirect(FormsAuthentication.LoginUrl)
ElseIf Session("login") = Nothing Then
FormsAuthentication.SignOut()
Session.Abandon()
Session.RemoveAll()
FormsAuthentication.RedirectToLoginPage("~/default")
Else
Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString)
Using cmd As SqlCommand = New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "select hashtable.Username, lastlogin, hashtable.HASHid, hashtable.compID, company_list.Company_Name from hashtable inner join company_list on company_list.CompanyID = hashtable.CompID where hashtable.username = '" + Session("login") + "'"
Dim dt As New DataTable()
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
dt.Load(reader)
userID.Text = "Welcome Mr. " + dt.Rows(0).Item("Username").ToString.Trim()
LastLogin.Text = dt.Rows(0).Item("lastlogin").ToString.Trim()
Session("Companydetl") = dt.Rows(0).Item("compID").ToString.Trim()
Session("lastused") = dt.Rows(0).Item("HASHid").ToString.Trim()
con.Close()
End Using
End Using
End If
Global.ASAX
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.User IsNot Nothing Then
If HttpContext.Current.User.Identity.IsAuthenticated Then
If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
Dim id As FormsIdentity = DirectCast(HttpContext.Current.User.Identity, FormsIdentity)
Dim ticket As FormsAuthenticationTicket = id.Ticket
Dim userData As String = ticket.UserData
Dim roles As String() = userData.Split(",")
HttpContext.Current.User = New GenericPrincipal(id, roles)
End If
End If
End If
End Sub
when I run below code the menu is not visible.
<% if (HttpContext.Current.User.IsInRole("Atul")) Then %>
Update Company Details
<% end if %>
and when I try to know the role of the current user it display blank.
please help
First up, you should always use parameters WHEN dealing with user input. You can get away using string concatenation for internal code, but when input comes from the web page, you REALLY want to use parameters.
So, for example, your code snip should be this:
Also, note that a sql command object has a connection, has a reader.
So LITTLE need to code over and over a seperate conneciton object and a reader - you do NOT need those - they eixst as part of the sqlcommand object.
eg this:
Dim strSQL As String
strSQL = "select hashtable.Username, lastlogin, hashtable.HASHid, hashtable.compID, company_list.Company_Name from hashtable " &
"inner join company_list on company_list.CompanyID = hashtable.CompID " &
"WHERE hashtable.username = #Login"
Using cmd As SqlCommand = New SqlCommand(strSQL,
New SqlConnection(ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString))
cmd.Parameters.Add("#Login", SqlDbType.NVarChar).Value = Session("login")
Dim dt As New DataTable()
cmd.Connection.Open()
dt.Load(cmd.ExecuteReader)
With dt.Rows(0)
userID.Text = "Welcome Mr. " + .Item("Username")
LastLogin.Text = .Item("lastlogin")
Session("Companydetl") = .Item("compID")
Session("lastused") = .Item("HASHid")
End With
End Using
So, note how I don't need a separate connection object, and I don't need a reader (they already exist as part of the sql command object. So, just trying to save your keyboard here!!
Next up:
To test/check for role membership? If you setup security tables correctly, then you should have something like this:
You REALLY want to ensure that your tables follow the standard asp.net security.
Now in above, my main contact table is custom, but the rest of the tables are the standard ones required and generated by running the sql scripts to setup security. The REASON why this is a HUGE deal? Then you can secuire ANY web page by simply dropping in and haveing a web.config file in any sub folder, and thus you can secure any web page AUTOMATIC without code based on the users role.
So, you can say use this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authorization>
<allow roles="PortalMaster" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
So now, any user to use any page in that sub folder with the above web config? They MUST be a member of PortalMaster - they can't even load that page if they try to - no code required.
And if you done this correct, to test for role membership, then you can and should use this:
If Roles.IsUserInRole("PortalMaster") then
' code goes here for user role = PortalMaster
End if
So you can and should be able to use Roles.IsUserInRole("some role name")
Dim roles As String() = userData.Split(",")
Above is a bad idea - the roles need to come from the Web_usersInRoles table.
If you need to display all roles for a given user, then you can do this:
Say we have a simple button + text box:
<br />
<asp:Button ID="Button1" runat="server" Height="34px" Text="Button" Width="170px" />
<br />
<asp:TextBox ID="TextBox1" runat="server" Height="188px" TextMode="MultiLine" Width="423px"></asp:TextBox>
The button code can be this:
For Each MyRole As String In Roles.GetRolesForUser()
TextBox1.Text &= MyRole & vbCrLf
Next
result:
And with this setup, then in say the master page, you can control/set/hide menu bar items like this:
<li id="mAdmin" runat="server" class="dropdown" ClientIDMode="Static">
so above is a menu bar - master page. With roles, we can now do this:
Me.mAdmin.Visible = Roles.IsUserInRole("SiteAdmin")
So, to run security on that site - you really - but really really really want to use and have the membership role tables setup correctly here.
So to test for membership in a role you can and should be able to use
Roles.IsUserInRole("some role name here") = true/false

ASP.NET / VB.NET : Generate Insert Command

I have all of my form variables in my codebehind, they were all retrieved using "Request.Form".
As Far as I Know..If I use the SQLDataSource to do this I have to use ASP.NET Controlls(which I do not want).
INSERT INTO Orders(FirstName, LastName, Email, PhoneNumber, Address, City, State, ZipCode, PaymentMethod, PromoCode, OrderStatus, Tracking, PPEmail, SubmissionDate) VALUES (#FirstName, #LastName, #Email, #Phone, #Address, #City, #State, 11111, #PaymentMethod', '0', 'New Order - Pending', '0', #PPEMAIL, #Date)
CodeBehind
Dim fPrice As String = CType(Session.Item("Qprice"), String)
Dim DeviceMake As String = CType(Session.Item("Make"), String)
Dim PaymentMethod As String = Request.Form("Payment Type")
Dim DeviceModel As String = CType(Session.Item("Model"), String)
Dim DeviceCondition As String = CType(Session.Item("Condition"), String)
Dim SubmissionDate As String = Date.Now.ToString
Dim FirstName = Request.Form("First")
Dim LastName = Request.Form("Last")
Dim City = Request.Form("City")
Dim Phone = Request.Form("Phone")
Dim Address = Request.Form("Address")
Dim State = Request.Form("State")
Dim Zip = Request.Form("Zip")
Dim Email = Request.Form("EMail")
Is there a way I can attatch my variables to the insert statment generated by the SQLDatasource, without having to manually code the parameters?
You could use FormParameter. This doesn't require any ASP.NET control so far I'm aware.
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:MyNorthwind %>"
selectcommand="SELECT CompanyName,ShipperID FROM Shippers"
insertcommand="INSERT INTO Shippers (CompanyName,Phone) VALUES (#CoName,#Phone)">
<insertparameters>
<asp:formparameter name="CoName" formfield="CompanyNameBox" />
<asp:formparameter name="Phone" formfield="PhoneBox" />
</insertparameters>
</asp:sqldatasource>
Pay special attention to Microsoft warning in relation to this mechanism
The FormParameter does not validate the value passed by the form element in any way; it uses the raw value. In most cases you can validate the value of the FormParameter before it is used by a data source control by handling an event, such as the Selecting, Updating, Inserting, or Deleting event exposed by the data source control you are using. If the value of the parameter does not pass your validation tests, you can cancel the data operation by setting the Cancel property of the associated CancelEventArgs class to true.
Its probably better that you forcibly attach the parameters. As you are getting your values from Form and Session (ick), parameterizing the SQL will give you some measure of protection.
You may want to explore code generation (A-la T4), this way you can point the codegen at a proc/table and it will generate the vb code to call it, attach the params and execute the statement.

error in nvarchar to date, date not supplied, either problem in onclick event or stored procedure or in gridview

For your information, I am using Visual Studio Professional 2010
Can someone please help me out, I think the #dateFound parameter is not supplied with a value on click event.
I have a gridview populated from stored procedure as given below.
<asp:SqlDataSource id="Sql20"
ConnectionString='<%$ ConnectionStrings:connectionString %>'
SelectCommand="dbo.StoredProcedure2"
Runat="server" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
The storedProcedure2 is as follow which is suppose to show all the data in gridview if #dateFound IS NULL, by default as below
ALTER PROCEDURE dbo.StoredProcedure2
(
#dateFound DATE
)
AS
/* SET NOCOUNT ON */
IF #dateFound IS NULL
BEGIN
SELECT
lc_orders_tb.lc_orderID,
lc_orders_tb.lc_orderSubTotal,
lc_orders_tb.lc_orderTotal,
lc_orders_tb.LRNo,
lc_orders_tb.LRDate,
lc_orders_tb.lc_orderPlacedDate,
lc_orders_tb.LInvoiceLoc,
lc_orderStatus_tb.lc_orderStatusDescrip,
lc_orderStatus_tb.lc_delType,
lc_tb.lc_compName,
lc_tb.lc_addCity,
(SELECT SUM(lc_orderQuantity)
FROM lc_orderQuantity_tb
WHERE
lc_orders_tb.lc_orderID=lc_orderQuantity_tb.lc_OrderID) as lc_orderQuantity
FROM lc_orders_tb
INNER JOIN
lc_tb ON lc_orders_tb.lc_id = lc_tb.lc_id
INNER JOIN
lc_orderStatus_tb ON lc_orders_tb.lc_orderID = lc_orderStatus_tb.lc_orderID
ORDER BY lc_orders_tb.lc_orderPlacedDate DESC
END
ELSE
BEGIN
SELECT
lc_orders_tb.lc_orderID,
lc_orders_tb.lc_orderSubTotal,
lc_orders_tb.lc_orderTotal,
lc_orders_tb.LRNo,
lc_orders_tb.LRDate,
lc_orders_tb.lc_orderPlacedDate,
lc_orders_tb.LInvoiceLoc,
lc_orderStatus_tb.lc_orderStatusDescrip,
lc_orderStatus_tb.lc_delType,
lc_tb.lc_compName,
lc_tb.lc_addCity,
(SELECT SUM(lc_orderQuantity)
FROM lc_orderQuantity_tb
WHERE
lc_orders_tb.lc_orderID = lc_orderQuantity_tb.lc_OrderID) as lc_orderQuantity
FROM lc_orders_tb
INNER JOIN
lc_tb ON lc_orders_tb.lc_id = lc_tb.lc_id
INNER JOIN
lc_orderStatus_tb ON lc_orders_tb.lc_orderID = lc_orderStatus_tb.lc_orderID
WHERE
convert(varchar(10), lc_orders_tb.lc_orderPlacedDate, 103) = #dateFound
ORDER BY lc_orders_tb.lc_orderPlacedDate DESC
END
RETURN
#dateFound will be supplied when clicked on a button click but by default, I mean, when page loads it is not supplied and therefore it should execute the first if statement but it different errors like #dateFound not supplied or error on converting nvarchar to date. The ELSE statement of the SP should get executed if #dateFound supplied from the textbox after clicking on the button. But I cant seem to work out. Please have a look at the click event of the button which is supplying the #dateFound
Protected Sub CustomGV3_onClick(ByVal sender As Object, ByVal e As EventArgs)
Dim connectionString As String =
WebConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand("dbo.StoredProcedure2", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue
("#dateFound", Format(txtBoxDateFrom.Text, "dd/MM/yyyy"))
Using con
con.Open()
cmd.ExecuteReader()
con.Close()
End Using
GridView3.DataBind()
End Sub
Can someone please help me out. Does it seem like I have a totally wrong approach ? Can someone please correct me.
awaiting your kind help plz..
Thanking You
Try changing your stored procedure to use a default value for the #dateFound parameter:
ALTER PROCEDURE dbo.StoredProcedure2
(
#dateFound DATE = NULL
)
AS
I finally got the answer from other forum, it worked by simply changing following in the SP
(
#dateFound DATE = '01/01/1900'
)
The above date is set as default as it will never be going to be in the database against which I will be checking by IF STATEMENT in SP. And in the aspx page to as below.
<SelectParameters>
<asp:ControlParameter ControlID="txtBoxDateFrom"
Name="dateFound" PropertyName="Text"
DbType="Date" DefaultValue="01/01/1900" />
Thanks to all contributor who tried to help me out here..

asp.net (web forms with VB.Net) connecting to a sql database

I'm trying to write a method in VB.net so that when I click a button it queries the database and returns all the values which match a textbox which is located next to the button. I have no idea how to do this, I assume in the onclick method for the button I will need to pull in the value from the textbox, connect to the database and display the results to a gridview?
Any help is greatly appreciated.
thanks :)
Marc
The two "best" options are to either use a Table Adapter or Entity Framework.
http://msdn.microsoft.com/en-us/library/bz9tthwx(v=vs.80).aspx (Table Adapter)
http://msdn.microsoft.com/en-us/library/bb399567.aspx (Entity Framework)
Both options will give you a GUI interface to build the connection and back end database queries. Entity Framework is the newer technology of the two. Table Adapters are probably easier to learn/understand if your unsure. (Que "easy" comments now)
I would give code examples but you'll have to understand some basics of either for them to make any sense. The basic examples in either link should be enough for what you need.
Both options will give you the ability to databind your datagrid to the results.
DISCLAIMER: This code is prone to SQL injection attacks and should not be used in a production environment. For testing only. Specifically:
strSQL = "SELECT * from Table where charindex ('" & TextBox1.Text & "', columnname) > 0 "
First in the web.config add this section that points to your database:
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
For the example, I've just used the standard database which is attached when you start a new vb.net web application in VisualStudio 2010.
Then in your Default.aspx, have something like this:
<asp:TextBox runat="server" ID="TextBox1"></asp:TextBox>
<asp:Button runat="server" Text="Button" ID="Button1" />
And in the code behind you could do something like this:
Imports System.Data.SqlClient
Public Class _Default
Inherits System.Web.UI.Page
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strSQL As String = String.Empty
' Define your select statement
strSQL = "SELECT * from Table where charindex ('" & TextBox1.Text & "', columnname) > 0 "
' Fire up SQLConnection with a DataReader
Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString)
Dim command As New SqlCommand(strSQL, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
Try
' Do some magic with reader.GetValue()
Catch ex As Exception
End Try
End While
reader.Close()
connection.Close()
End Using
End Sub
End Class
Ofcourse you'd have to validate the textbox.text before placing it directly into the select statement, but this will do the trick.
The 'CharIndex' will loop through the column specified as the second parameter and check if there's a match between the column data and the textbox.text, if so it will return the row.
The reader will loop through the results and with the reader.GetValue you can retrieve the data and do your magic.
Instead of using a SQLDataReader you can of course attach it to a Databound Grid or something else...

Resources