Question

How do you use the SQLDataSource object in the VB code behind module?

Asked by: monacoassociates

I am trying to upgrade a website from Visual Studio 2003 to VS 2005, taking advantage of some of the new controls and features available.  In the VS 2003 version, I am accessing data in the VB code using a connection object.  In the VB 2005 version, I would like to create an SQLDataSource object in design view.  My question is, how do I get a look at the data in the VB code behind module in order to code against it?  

For exampe, I have the following code in my Visual Basic code behid module:
Dim conn As OleDbConnection = New OleDbConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString"))
Dim cmd As New OleDbCommand(loginSQL, conn)
Dim dbReader As OleDbDataReader
conn.Open()

Try
   dbReader = cmd.ExecuteReader()

   If dbReader.Read Then
      If (dbReader.GetBoolean(dbReader.GetOrdinal("Hide"))) Then
         lblErrorMsg.Text = "Your EC3 account has been deactivated.  Please see your EC3 administrator."
         lblErrorMsg.Visible = True
         Exit Sub
      End If
      Session("SSN") = (dbReader.GetString(dbReader.GetOrdinal("Social Security Number")))
      Session("UserName") = (dbReader.GetString(dbReader.GetOrdinal("Full Name")))
      Session("Security") = (dbReader.GetString(dbReader.GetOrdinal("Security")))
      Session("Access") = (dbReader.GetBoolean(dbReader.GetOrdinal("All Consumers")))
     dbReader.Close()
      conn.Close()
      checkPrefs()
      blErrorMsg.Visible = False
      Response.Redirect("testform.aspx")
Else
   lblErrorMsg.Text = "User Name and/or Password invalid."
   lblErrorMsg.Visible = True
   dbReader.Close()
   conn.Close()
End If
Finally
   conn.Close()
End Try

How can I do this using the SQLDataSource I have set up to execute the SQL?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-06-25 at 11:37:57ID22656507
Tags

sqldatasource

,

vb

Topics

Visual Basic Programming

,

Visual Studio

Participating Experts
1
Points
500
Comments
11

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. SQLDATASOURCE
    Hi All, I am using C#, ASP.NET... How can i programatically(in C#) run a store procedure, pass parameters and bind the data to my gridview using my sqldatasource? The code below doesnt work..but it can give you some idea of what i am trying to do.... SqlDataSource1.Selec...
  2. SqlDataSource and foreach
    New to ASP.NET - transitioning from ASP ... I'm trying to create PushPins for a Virtual Earth (live maps - http://msdn2.microsoft.com/en-us/library/bb429619.aspx) map from addresses derived from a SqlDataSource by doing a "foreach" type of step. Don't let the map...
  3. Should I use SqlDataSource or SqlConnection (which is be…
    During the last year, when I was first learning about vb.net and trying to take my first baby steps writing data access code (without using the drag-and-drop tools) I first latched onto using SqlDataSource. Since then I have become aware of SqlConnection, but I don t really ...
  4. SqlDataSource Control Issue
    Hello, I recently found a tutorial that I really need to implement by today and so far everything is working EXCEPT when I select the plus sign to expand to view details from the GridView RowCreated Event Handler. Tutorial: http://yasserzaid.wordpress.com/2008/12/21/ajax-c...
  5. sqldatasource
    I am binding data to a gridview and various dropdown lists on my page, I’ve been told using the sqldatasource is not good practice, and I should use code to bind the data. But I cannot see any reason why I should not use numerous sqldatasources on my page. Can you think of a...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: traxionPosted on 2007-06-25 at 13:24:27ID: 19358873

This SQLDataSource is great for bindable controls (such as hte GridView).  In your case, I would consider sticking with the dataread.  But if you're going to be using something such as the GridView control, drop the SQLDataSource onto your project.  You can set the Select Command as follows programatically:

SqlDataSource1.SelectCommand = loginSQL

 

by: monacoassociatesPosted on 2007-06-26 at 10:25:21ID: 19365908

Here is the problem we are having with the data reader.  We need to use many data grids in our website, and there seem to be definite advantages in creating them in design view.  But we also need to manipulate individual fields of data with code.  And we need a connection string in the web config file rather than a fixed connection to the database.

When we create a data grid in designer view, we end up with a connection string in the "connection string" section of the web config file.  The connection string we are using with our data reader is in the "app settings" section of web config.  And we're just too dumb to figure out a way to get the code-created connection and the designer-created connection to use the same connection string.  We tried using the "ConnectionStrings" option for the OleDBConnection, but couldn't find any syntax that would work.  And the Help files are NO HELP.   So, if you could tell us how to get these two types of connection to use the same connection string, that would be an alternative way to solve our problem.

We are, in case you haven't already guessed, inexperienced at web development.  Any help will be appreciated.  

 

by: traxionPosted on 2007-06-26 at 11:04:13ID: 19366246

Well, there are a couple of different scenarios to consider.  If you're going to use the SQLDataSource you'll want to do a couple of things:

For 1, the DataGrid is getting to be a bit obsolete as the "GridView" control offers much more flexibility.  So, you'll want to create your GridView controls in design view.  Create an SQLDataSource control in designview.  For the GridView, set DataSourceID to the ID of the SQLDataSource, you can also do this programmatically:  Example:
GridView1.DataSourceID = "SQLDataSource1"

Now, there are different commands for the SQLDataSource:
SqlDataSource1.SelectCommand = "Some Select SQL"
SqlDataSource1.UpdateCommand = "Some Update SQL"

For the GridView you'll want a DataKey Field that will be the unique ID of your record. This will be used for the SqlDataSource when doing the updating.  The trick to using hte SQL DataSource is using the correct provider.  For OleDB:
SqlDataSource1.ProviderName = System.Data.OleDb

I am currently developing a site using the SQLDataSource with MySQL, in which case I'm using the MySql Connector .NET (ADO with much better performance than OleDB).  It's a bit more tricky to get working if the MySqlConnector hasn't been installed on the remote server as you have to register your own ProviderFactory.  I added the following to my Web.Config file:
<system.data>
    <DbProviderFactories>
      <add name="MySQL Data Provider" invariant="MySQL.DataSource" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=5.1.2.2, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>

Then I just use:  SqlDataSource1.ProviderName=  "MySQL.DataSource"

Ok, now is the tricky part.  You have a couple of options.  You can use a different SQLDataSource for each GridView control if you have multiples, or as I do, use the same SQLDataSource for different gridview controls.  I only have one gridview control visible at a time, so I use the same SQLDataSource and just change the SELECT Commands and do the following:
Gridview1.DataSourceID = Nothing
Gridview2.DataSourceID = "SQLDataSource1"

If you are going to have more than one GridView visible at a time, use multiple SQLDataSource controls.  You may also use Parameters with your DataSources.  I have created a function that I call when needed called InitDataSource to set up my initial datasource settings:

 SqlDataSource1.ConnectionString = ConfigurationManager.AppSettings("ConnectionString")
        SqlDataSource1.ProviderName = "MySQL.DataSource"
        SqlDataSource1.SelectCommand = "SELECT DistrictID, DistrictCode, DistrictName FROM Loc_Districts ORDER BY DistrictCode ASC"
        SqlDataSource1.UpdateCommand = "UPDATE Loc_Districts SET DistrictCode=?DistrictCode, DistrictName=?DistrictName WHERE DistrictID=?DistrictID"
        SqlDataSource1.DeleteCommand = "DELETE From Loc_Districts WHERE DistrictID=?DistrictID"

Notice the use of ?DistrictID.  This is a Parameter for the Query.  If you're using MySQL you'll use the ? to signify the parameter.  If you're using other Databases, such as MSSQL, you'll use @ so it would actually be @DistrictID.

For my GridView, I have DistrictID set as the "DataKeyNames" properties of the GridView.  This allows me to do Inline Editing in my GridView.  You can also use "ItemTemplates" for the edit item columns and even mark some columns as not editable.

Now...having read this...let me know which questions are still unanswered and I'll be more specific.

Thanks,

Dustin

 

by: traxionPosted on 2007-06-26 at 11:11:13ID: 19366292

I forgot to give you the second scenario. :)  Rather than using the OleDbDataReader, use the OleDbDataAdapter and fill a DataTable.

Dim dtSample As New DataTable
objDataAdapter.Fill(dtSample)

Now for your gridview:

Gridview1.DataSource = dtSample
Gridview1.DataBind()

This will allow you to clean up each datatable when you're done using it...if you'd rather you can create a dataset:

Dim dsData As New DataSet

and for your first Query:
objDataAdapter.Fill(dsData, "People")

Then for your second query
objDataAdapter.Fill(dsData, "Awards")

Substitute your desired table names.  Now to access these, say you have the following queries:
Query1:  "SELECT PersonID, LastName, Email FROM tblPeople"
and
Query2:  "SELECT AwardID, AwardName, AwardType FROM tblAwards"

Now, you would access these as follows...to get the person's name and email:

Response.Write("Name: " & dsData.Tables("People").Rows(0)("LastName") & "<br>")
Response.Write("Email:" & dsData.Tables("People").Rows(0)("Email")

You could also iterate, so to list all award names and types from table 2:
Dim i As Integer
For i = 0 to dsData.Tables("Awards").Rows.Count - 1
         Response.Write(dsData.Tables("Awards").Rows(i)("AwardName") & " - " & dsData.Tables("Awards").Rows(i)("AwardType") & "<br>")
Next

 

by: monacoassociatesPosted on 2007-06-26 at 13:22:41ID: 19367516

Thanks, Dustin.  You've given me a lot to go on.  It will take a day or two for me to try to put this into action and see if it gets me where I want to go.  And I'm gonna be on the road for several days, not sure how much time I'll have to give it--so more later.
Lou

 

by: traxionPosted on 2007-06-26 at 14:29:09ID: 19367994

No problem.  ;)  Let me know how it comes out.

 

by: monacoassociatesPosted on 2007-06-26 at 14:45:36ID: 19368121

I have a couple of questions about your comments/code.  
1.  I notice that when you provide a connection string in code for your SQLDataSource, the connection string is in "appsettings", which is the same place my OLEDbConnectionString is.  We found when creating the SQLDataSource in design view, we ended up with a connection string in "connectionStrings" so we now are accessing the same connection string in our web config file under two different variable names in two different sections.  That seems like it could lead to trouble.  Or is it no problem?  If it is no problem, I can continue using my datareader as is, and try to use all these useful ideas you have suggested for other pages yet to be developed.
2.  We are using an Access database.  There must be an ADO connection for Access, but I've no idea how to get to it.  With all the trouble we are having getting this thing off the ground, I am inclined to think, "If it ain't broke, don't fix it."  Is OLEDb all that bad?

 

by: traxionPosted on 2007-06-27 at 06:48:39ID: 19372178

For Q1:  There is actually a designated area for "ConnectionStrings" in the Web Config file, which is where the SQL Data Source created it when you created it in design view.  I noticed in your code you referenced one in AppSettings so I used that example in the sample code.  Either place is really fine, but I would use one or teh other.  There is nothing wrong with assigning the "AppSettings" ConnectionString to your SQLDataSource.  The "ConnectionStrings" node of the web.config file is the most 'proper' place to store it though, but I believe this is only for symantics.

Q2:  ODBC is slower (and more legacy) than ADO, however you are limited to the appropriate providers being available for the database system you choose.  I use MySQL for some web projects (strictly due to licensing costs of MSSQL Server) and it works just great, however, there are some licensing restrictions with it as well.  The bottleneck in your situation will be the Access database.  Your overall performance will suffer somewhat when using hte file based Access database rather than a dedicated server, but for small projects it should work fine.  This all depends on your application.  It also depends on the drivers and such doing the connection.  I re-read my original posts and I misspoke a bit and didn't realize it.  OleDB is part of ADO .NET.  I have chosen to use the MySQL ADO Providers rather than using a DSN through ODBC and using drivers that have to be installed on the server.  If you're using OleDB, you're doing just fine.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...