Database troubleshooting in ASP.NET 2.0

Posted on 2008-06-20
Last Modified: 2012-06-27
I have a simple SqlDataSource control that retrieves six category names and their Id from a Category table using the SELECT statement:

SelectCommand="SELECT [Name], [CategoryId] FROM [Categories] ORDER BY [Name]"

I have a DropDownList bound to the SqlDataSource and I see the retrieved categories fine in the drop down list, so this is working fine.  

But Id like to try to look inside whats happening using the Selected event handler for the SqlDataSource.  
At Microsoft says that for the Selected event:

"Occurs when a data retrieval operation has completed. Handle the Selected event to examine the values of output parameters after a data retrieval operation has completed. The output parameters are available from the SqlDataSourceStatusEventArgs object that is associated with the event."

And they give some sample code you can put in the Selected event handler to show the command parameters:

Protected Sub categoriesDataSource_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs)
        Dim cmd As IDbCommand
        cmd = e.Command
        Dim param As SqlParameter

        Label1.Text = "Parameter return values: "

        For Each param In cmd.Parameters

            ' Extract the name and value of the parameter.
            Label1.Text = Label1.Text & param.ParameterName & " - " & _


    End Sub ' OnSelectedHandler

The first problem is that the For Each code doesnt seem to work for me.  I can break at the "Label1.Text =" line and then step to the For Each, but stepping into the For Each goes directly to the End Sub line, as if there were 0 parameters.  But I can see by opening up the e > command > parameters that theres a bunch of stuff there, like count (0), IsFixedSize (False).  Is count=0 the problem, maybe?

The second problem is that I dont see anything in e that shows me the output parameters after the data retrieval operation.  Im expecting to see the actual category names retrieved from the Cataegory table, like Cars, Boats, etc.

Does anyone know whats going on here and why Im not seeing what I expect?

Thanks for any help.
Question by:steva
  • 3
  • 3
LVL 37

Expert Comment

Comment Utility
What does your full sqldatasource look like?

>>For Each, but stepping into the For Each goes directly to the End Sub line, as if there were 0 parameters

It sounds like you're expecting the rows of data to be the "parameters"?
If you look at the example here:
the sqldatasource in the example is:

<asp:sqlDataSource ID="EmployeeDetailsSqlDataSource"
  SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID"

  InsertCommand="INSERT INTO Employees(LastName, FirstName) VALUES (@LastName, @FirstName);
                 SELECT @EmpID = SCOPE_IDENTITY()"
  UpdateCommand="UPDATE Employees SET LastName=@LastName, FirstName=@FirstName
                   WHERE EmployeeID=@EmployeeID"
  DeleteCommand="DELETE Employees WHERE EmployeeID=@EmployeeID"

  ConnectionString="<%$ ConnectionStrings:NorthwindConnection %>"

    <asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />

    <asp:Parameter Name="EmpID" Direction="Output" Type="Int32" DefaultValue="0" />


and running your code with the "for each" loop would return "EmpID" because of the:
    <asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />

so the line:
For Each param In cmd.Parameters

is actually looking through the parameter collection for the sqldatasource for actual parameters defined in the sqldatasource...
it won't return the actual data...

Author Comment

Comment Utility
Ok, I got it.  In my simple SqlDataSource none of the values were were parameterized  (place held in SELECT with @ and parameter defined farther below in a SelectParameters section) so that's why e > Command > Parameters > Count was zero and why the For Each didn't execute anything. If I include a parameter that comes from a QueryString,  it is parameterized, Count=1 and I do step into the For Each one time to show this parameter.

Still this is a bit disappointing because I was expecting to see the actual data retrieved by the SELECT statement, not the parameters of the SELECT request.  Is there no way to do this? I know I could probably execute a SELECT in the handler and then look at a dataview object, but I want to know what actually came back from the SELECT in the page.  

(Thanks again for your help).  
LVL 37

Expert Comment

Comment Utility
>>execute a SELECT in the handler and then look at a dataview object, but I want to know what actually came back from the SELECT in the page.  

That's pretty much what you have to do, as in my example below...still based on that MS example
<%@ Page Language="VB" %>

<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<script runat="server">


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim dv As DataView

        dv = CType(Me.EmployeeDetailsSqlDataSource.Select(DataSourceSelectArguments.Empty), DataView)

        For Each row As DataRow In dv.Table.Rows

            Response.Write(row("LastName").ToString() & "<br />")


    End Sub


<html xmlns="">

<head id="Head1" runat="server">

    <title>Untitled Page</title>



    <form id="form1" runat="server">


            <asp:SqlDataSource ID="EmployeeDetailsSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString1 %>"

                DataSourceMode="DataSet" DeleteCommand="DELETE Employees WHERE EmployeeID=@EmployeeID"

                InsertCommand="INSERT INTO Employees(LastName, FirstName) VALUES (@LastName, @FirstName); 

                 SELECT @EmpID = SCOPE_IDENTITY()" SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID or 1 =1 "

                UpdateCommand="UPDATE Employees SET LastName=@LastName, FirstName=@FirstName 

                   WHERE EmployeeID=@EmployeeID">


                    <asp:Parameter DefaultValue="0" Name="EmpID" Type="Int32" />



                    <asp:Parameter DefaultValue="0" Direction="Output" Name="EmpID" Type="Int32" />



            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" DataSourceID="EmployeeDetailsSqlDataSource">






Open in new window

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.


Author Comment

Comment Utility
First , thanks for the great examples.

Now if we could consider the line:

dv = CType(Me.EmployeeDetailsSqlDataSource.Select(DataSourceSelectArguments.Empty), DataView)

in your page load handler.

1.  It looks like  this executes the database access specified by the  EmployeeDetailsSqlDataSource control, complete with whatever SELECT statement was provided with the control.  And then the same access is made again later in the   body, where the EmployeeDetailsSqlDataSource control is specified again.  Is that right?

2. What is the the "Me" part of "Me.EmployeeDetailsDataSource..."

3. I notice that

  dv = EmployeeDetailsSqlDataSource.Select(DataSourceSelectArguments.Empty)

works as well as

  dv = CType(Me.EmployeeDetailsSqlDataSource.Select(DataSourceSelectArguments.Empty), DataView)

so why the extra stuff?

4.  And finally, what is the "DataSourceSelectArguments.Empty" parameter to Select statement? Does this somehow  signify "whatever is in the SELECT statement of the SqlDataSource control"  ?

I apologize for all the baby questions but each response you make puts a brighter light on  the subject, and I do appreciate it.  

LVL 37

Accepted Solution

samtran0331 earned 500 total points
Comment Utility
1. Yes.
I'm not a big fan of some of the "new" 2.0 features like using a SqlDatasource.
All my coding, I still use sqldataadapters and datatables etc.
To me, SqlDatasource was meant for MS's marketing of "write programs without knowing how to code" mentality of being able to drag and drop your way to a full application.
For simple stuff, it works great, but as soon ass you have to do "real" coding, it becomes more work to do simple this question for example.
2. "Me" just keeps context and helps the Intellisense so I don't have to type as much, in some scenarios, it is possible to have 2 or more objects available to you with the exact same name, using "Me" helps keep track of which one to use.  It's the equivalent of "this" in C#.
For this question, not necessary.
3.  Without the Ctype conversion, you rely on the .Net framework to implicity make that conversion for you; so even if you don't type it out, it's happening behind the scenes.  Writing it out always makes sure you convert to the right type.  There are setting in VB that will force you to do all conversions (Option Explicit = True)...and c# wouldn't let you get away with it at'd have to convert.
4. Basically yes.

Author Comment

Comment Utility
Many thanks.  I gave you the best score possible, though it still doesn't seem like enough for all your help. Experts Exchange should allow the questioner to specify  a "preferred answer provider" where you would get the question four hours before anyone else.

Thanks again.

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now