locked
programmatic access to sqldatasource dataset RRS feed

  • Question

  • i'd like to take advantage of all the benefits of the new sqldatasource control to do quick queries & bindings, but also retain the flexibility of the previous ways of data access (i.e. sqlcommands/sqldataadapters) to fill datasets.  is there a way to have programmatic access to the dataset that is filled after a sqldatasource queries a db?  i dont want to display all the columns queried in my gridview, but i want that data available for further manipulation without having to run another query.  am i going about this the wrong way, or have i just not stumbled upon the solution?

    thanks,

    david

    Tuesday, January 31, 2006 11:11 PM

Answers

  • You can certainly do something like this.  I programmatically created an SqlDataSource, called the Select Method on it, retrieved the DataView, and converted the results to a DataTable that I can manipulate as I see fit.

     

    string connectionString = "...Northwind Connection String...";
    string selectSql = "SELECT [CategoryID], [CategoryName] FROM [Categories]";

    DataSourceSelectArguments args = new DataSourceSelectArguments();

    SqlDataSource dataSource = new SqlDataSource(connectionString, selectSql);
    DataView view = (DataView)dataSource.Select(args);

    DataTable table = view.ToTable();

     

    Does that help?

    Regards,

    Dave

    Wednesday, February 8, 2006 9:20 PM

All replies

  • Did you ever find your solution for this?  I have the same question.

    Mitch

    Wednesday, February 8, 2006 2:19 PM
  • nope, no luck finding a solution...yet.  i find it interesting that over 200 people have read my post but noone has yet posted a solution (much less a suggestion).  this tells me that we aren't the only ones out there trying to get this to work.  pains of living on the bleeding edge i suppose. :-|  i've checked several .net 2.0 books but none go any deeper into the gridview/sqldatasource/dataset relationship than how to initially set one up...
    Wednesday, February 8, 2006 5:24 PM
  • You can certainly do something like this.  I programmatically created an SqlDataSource, called the Select Method on it, retrieved the DataView, and converted the results to a DataTable that I can manipulate as I see fit.

     

    string connectionString = "...Northwind Connection String...";
    string selectSql = "SELECT [CategoryID], [CategoryName] FROM [Categories]";

    DataSourceSelectArguments args = new DataSourceSelectArguments();

    SqlDataSource dataSource = new SqlDataSource(connectionString, selectSql);
    DataView view = (DataView)dataSource.Select(args);

    DataTable table = view.ToTable();

     

    Does that help?

    Regards,

    Dave

    Wednesday, February 8, 2006 9:20 PM
  • Hi David,

    Did you take a look at the method SqlDataSource.GetView method?  This method returns the underlying SqlDataSourceView that holds the data. Depending on what you are trying to accomplish, you can either call the SqlDataSource.Select method directly and manipulate the data you get or you could try manipulating the underlying SqlDataSourceView in a handler for the SqlDataSource.Selected event. You could also set the EnableCaching property to true for the SqlDataSource which will cache the data for you so that you don't have to hit the db again and then use the GetView method to get the view and modify the displayed data using the FilterExpression property.

    Does that help?
    Imran.
    Wednesday, February 8, 2006 9:25 PM
  • thanks for the suggestion.  ive looked at it for a couple of days now but have not been able to come up with a solution using the GetView method.  have you had any success with the implementation you describe?  if you could post some sample code, that would be great.

    thanks again

    Tuesday, February 21, 2006 3:56 PM
  • The post by David Hayden worked for me.  I was able to use my existing SQLDataSource object and use its resultset for a DataList.

    string s_sql = "";

    s_sql = "SELECT Clients.*,CFARS.*,Therapists.* " +

    "FROM CFARS INNER JOIN Therapists " +

    "ON CFARS.TherapistID = Therapists.TherapistID INNER JOIN Clients " +

    "ON CFARS.ClientID = Clients.ClientID " +

    "WHERE Clients.SSN = '" + Request.QueryString["SSN"] + "' AND " +

    "CFARS.CFARSID = '" + Request.QueryString["CFARSID"] + "'";

    ClientDetailSource.SelectCommandType = SqlDataSourceCommandType.Text;

    ClientDetailSource.SelectCommand = s_sql;

    DataSourceSelectArguments args = new DataSourceSelectArguments();

    DataView view = (DataView)ClientDetailSource.Select(args);

    DataTable table = view.ToTable();

    string fullDate = table.Rows[0].ItemArray[7].ToString();

     

    This is called in a separate function from page load, of course this is only the stripped out essentials and not the whole function.  All I needed to get out of the result set was the date field to place elsewhere on the page aside from the DataList I was already using.

    Thank you Mr. Hayden.

    Wednesday, November 15, 2006 8:42 PM
  • Had the same problem. Cobbled this together from other posts and it looks promising.  I have a DetailsView fed by a SqlDataSource and I wanted one field value that was in the returned Select query from a stored procedure but was not bound or displayed in the DetailsView and I couldn't find a way to get at it to use elsewhere.

    First I declared an output parameter to the SelectParameters tag (input parameters omitted)

    <SelectParameters><asp:Parameter Name="return_value" Direction="output" Type="Int32"/><SelectParameters>

    Then I declared an output parameter in the stored procedure  @return_value int OUTPUT

    Then filled the variable after my full Select statement ran in the stored procedure.

    SELECT conID, compID, propID......<long select statement to feed the DetailsView>

    SELECT @return_value = compID from tblWhatEver WHERE whatever = @whatever

    Then in my SqlDataSource_Selected event I pulled that returned value out.

    dim i as integer = e.Command.Parameters("@return)value").Value

    I hope this is close to what you needed.

    Mike MCAD

    PS If anyone finds a way to pull the full dataset out of a bound SqlDataSource control in its normal, automated select I'd sure like to see it.

     

     

     

    Sunday, November 26, 2006 3:17 PM
  • Small update to the above. Because the DetailsView depends on the selection from a dropdownlist in which I put one of those dummy lines to seed it - "Please Select a Contact" the SqlDataSource_Selected event came in with a null value for that parameter value when page loaded.

    I had to protect from that possiblity in the SqlDataSource Selected event like this

    If Not IsDBNull(e.Command.Parameters("@return_value").Value) Then

     

    Sunday, November 26, 2006 4:09 PM
  • Hi, I'm pleased this worked for you....I have been struggling with the same issue in getting data out of a programmatic SQL select statement....like....

     

    ProfileDataSource.SelectCommandType = SqlDataSourceCommandType.Text

    ProfileDataSource.SelectCommand = "SELECT ConfID FROM ADMIN WHERE Conference_Name = PDValue"

    ..the Admin table only has 2 columns: ConfID and Conference_Name...

    I don't understand your 

    DataSourceSelectArguments args = new DataSourceSelectArguments();

    statement....I tried just pasting it in but got errors....must be missing something

    All I want to do is get the ConfID value.......I'm a real novice but have spent hours trawling through the forums to try and find out how to do what I thought was a pretty simple thing....hope you or others can help..

     

    Thursday, November 30, 2006 11:58 AM
  • Here is a simple way to get to the data stored in an SqlDataSource that is setup using the default dataset access type.   This example is based on a dropdownlist that is based on a "select * from table" that only uses 1 column for the text/value on the drop down, but we want to get to the other columns for auto-population of various form fields.

    We call this code when the dropdownlist changes index.... this is sample code, just dumps to the web output, but you get the idea...

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

    ' Get the calling drowdown that triggers this subroutine
    '
    Dim this As DropDownList = sender

    ' Setup my dataview
    '
    Dim dv As System.Data.DataView = CType(Me.SqlDataSource1.Select(DataSourceSelectArguments.Empty), System.Data.DataView)

    ' Get the specific row based on the pulldown item selected
    '
    Dim dr As DataRow = dv.Table.Rows(this.SelectedIndex)

    ' Show the matching data from the SQL data retrieval
    '
    Response.Write("Mfg: " + dr.Item("name") + "<br>")
    Response.Write("Model: " + dr.Item("social") + "<br>")
    Response.Write("Category: " + dr.Item("dob") + "<br>")


    End Sub


    HTH,
    Lance Cleveland, Founder
    Charleston Software Associates (charlestonsw.com)
    Cyber Sprocket Labs (cybersprocket.com)
    Monday, December 11, 2006 12:56 AM
  • If I understand correctly, the desired solution would be some method of using

    Protected Sub mySqlDataSource_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles mySqlDataSource.Selected

    Dim dv As SqlDataSourceView = ???

    '''' Modify data here and then allow the normal binding process to occur

    End Sub

    I personally am also looking for the same solution, and am currently trying to figure this out myself.  Someone had mentioned a "GetView" function that does not appear to exist - or I'm looking in the wrong place for it.  Any sample code on that usage would be appreciated.

    Thursday, December 28, 2006 8:27 PM
  • Hello,
    I am pretty new to coding and am running into a problem. I have tried looking thru the forums and this thread is as close to what I need as I have been able to find.

    Here is the issue.

    I have 2 db's one is sql and one is oracle. I have the Gridview pulling the data from the sqlserver db.
    I am using the rowdatabound to get my select parameter this select statement just verifies that the data is in the oracle table.

    My problem is I am having problems getting the data out o fthe view to match against the cell in the row.

    It keeps on telling me I need to use the New keyword ont he line "Dim dr As System.Data.DataRow = dv.Table.Rows(1)"

    If anyone could take a peek at this I would be grateful. :)

    Jaden

     

    The code

    Protected Sub GridView2_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)

    Dim p As New Parameter

    p.Name = "shipid"

    p.Direction = Data.ParameterDirection.Input

    p.Type = TypeCode.String

    SqlDataSource2.SelectParameters.Add("p", e.Row.Cells(4).Text.ToString)

    SqlDataSource2.SelectCommand = "select shipment_num from apps.rcv_shipment_headers where shipment_num = :shipid"

    Dim dv As System.Data.DataView = CType(Me.SqlDataSource2.Select(DataSourceSelectArguments.Empty), System.Data.DataView)

    Dim dr As System.Data.DataRow = dv.Table.Rows(1)

    TextBox2.Text = dr.Item(1)

    End Sub

    • Proposed as answer by Naomi N Thursday, November 26, 2009 8:00 AM
    Thursday, March 15, 2007 12:50 AM
  •  

     

    Quick and dirty solution to this is to do the following...

     

    in the HTML...

    <div id="productname" >

    <asp:Label ID="Label1" runat="server" Text='<%# this.UpdateTitle(Eval("Name")) %>'></asp:Label>

    </div>

     

    In the Code...

    protected string UpdateTitle(object newValue)

    {

    this.Title = newValue.ToString();

    return newValue.ToString();

    }

     

     

     

     

     

     

    Tuesday, June 12, 2007 11:15 PM
  • DataView view = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

    DataTable table = view.ToTable();
    DataSet ds = new DataSet();
    ds.Tables.Add(table);


    • Proposed as answer by Naomi N Thursday, November 26, 2009 8:15 AM
    Friday, July 13, 2007 3:56 AM
  • As far as I can see, it is not a dataset (as such) behind the databound controls.

     

    If you just want to 'lift' the values from a sub-control or two, this may help:

     

    on my page I have a formview (databound) control called "FormViewEditMember"

    inside that control I have some text boxes, one called "txtMemberName"

     

    Dim fv1 As FormView              ' if you use a different type of databound control, change this!

    Dim fv2 As TextBox                 ' if you are looking for a different type of control, change this!

     

    fv1 = Me.FindControl("FormViewEditMember")   ' copy of a control within my form (me)

    fv2 = fv1.FindControl("txtMemberName")            ' copy of the subcontrol within the control

    Me.txtOut.Text = fv2.Text                                 ' copy the text from the subcontrol to a separate control on the form

     

    repeat the last two lines for each control you want to lift a piece of info from.

     

    Thursday, September 13, 2007 5:42 AM
  • Code in vb

    (its nearly the same but get the data directly from DataView)

     

    Dim dv As System.Data.DataView

    dv = SqlDataSourceUsers.Select(DataSourceSelectArguments.Empty)

     

    tbxFirstName.Text = dv.Table.Rows(0).Item("FirstName_User")

    txbLastName.Text = dv.Table.Rows(0).Item("LastName_User")

    .

    .

    .

    .

     

    Sunday, September 23, 2007 4:28 PM
  • For a sqldatasource whose type is datareader, I access the datareader this way in VB.NET:

    Imports System.Data
    Imports System.Data.Common
    Imports System.Data.SqlClient

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim DataBytes As Byte() = New Byte(15) {}
    Dim rdrSql As SqlDataReader = DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty),   SqlDataReader)
              While rdrSql.Read()
                       DataBytes = rdrSql("Password")
              End While
              rdrSql.Close()
    End Sub

    BTW, DataBytes is converted from Binary to a string and saved in a hidden input.
     
    Wednesday, April 2, 2008 3:41 PM
  • Yes, I need exactly that. I have a SQLDataSource and my GridView is based on it. I need to copy this dataset into a session. I don't want to do another select, I want to be able to grab dataset in Selected event.

     

    I think I found my solution here

    http://msmvps.com/blogs/egoldin/archive/2006/12/27/how-to-get-datatable-out-of-sqldatasource.aspx

     

    In other words, instead of using SQLDataSource_Selected we need to use GridView_RowDataBound event.

     

    Sounds like a great idea for me.

    Friday, August 29, 2008 4:48 PM
  • i'd like to take advantage of all the benefits of the new sqldatasource control to do quick queries & bindings, but also retain the flexibility of the previous ways of data access (i.e. sqlcommands/sqldataadapters) to fill datasets.  is there a way to have programmatic access to the dataset that is filled after a sqldatasource queries a db?  i dont want to display all the columns queried in my gridview, but i want that data available for further manipulation without having to run another query.  am i going about this the wrong way, or have i just not stumbled upon the solution?

    thanks,

    david


    Session(

    "data") = GridView1.DataSourceObject
    use this


    Creativity is the only Tool that a Programmer is Gifted with.......
    Wednesday, September 9, 2009 10:11 AM
  • I don't think it's a good idea to save dataset in a session.
    Premature optimization is the root of all evil in programming.

    Donald Knuth, repeating C. A. R. Hoare

    My blog
    Thursday, September 10, 2009 3:24 AM
  • Thank you all for your posts..  I wanted to share my simple solution where I had an existing gridview and formview both using a sqldatasource.  I was selecting and sorting on a field called 'sort_order'.

    My SqlDataSource had the parameters setup in design view and using this method it was still able to use the querystring and dropdownlists which are being feed into my SelectCommand.

    What I needed to do was increment the sort_order so that the formview would append the newly inserted item at the bottom.  As I was already sorting the list I used the following code in the formview prerender.  As I had a textbox in the insert template of the fownview which was already bound to the sort column I was not able to insert my own default value without breaking the binding to SqlDataSource1.  That is why I wanted to set the textbox behind the scenes, so to speak.

        protected void FormView1_PreRender(object sender, EventArgs e)
        {
            TextBox txtSort = (TextBox)FormView1.FindControl("sort_orderTextBox");
            
            DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
    
            DataRow dr = (DataRow)dv.Table.Rows[dv.Table.Rows.Count-1];
    
            txtSort.Text = (Convert.ToInt32(dr["sort_order"])+1).ToString();
        }
    Thanks again to everyone who contributed to this simple solution.


    ~C
    Wednesday, September 16, 2009 7:52 PM
  • If you want to access the DataSet rows in the SqlDataSource (e.g. to find out if any data was returned from the database query) here is a technique you can use.  I use this technique to check if the SqlDataSource Select returned any rows to a GridView and if not, I display a No Records Found message.

    Add the OnDataBound event to your GridView like this:

    ondatabound="gvCustomerServiceHistory_DataBound"

    The DataBound event will be called right after the DataSet from the SqlDataSource is bound to the GridView control, so it's the perfect place to check and see if any rows were found.  Next add the code for the event handler:

    protected void gvCustomerServiceHistory_DataBound(object sender, EventArgs e)
        {
            if (gvCustomerServiceHistory.Rows.Count < 1)
                lblNoResults.Text = "No customer service notes in history yet.";
            else
                lblNoResults.Text = "";
        }
    Thursday, November 12, 2009 4:35 AM
  • Hi!

    I've had the similar problem, except on a FormView control. Working with the SqlDataSource control (on the aspx form). To get access to the "Current" data row being supplied by SqlDataSource to the FormView Control, Supcribe to the FormView's OnDataBound event. This is fired after the form is bound with data. Then

    to get the current row you can do

    DataRowView row = (DataRowView)this.FormView1.DataItem;

            if (row == null) return;

    // now you use standard row syntax to get values out of the source.

    var someThing = row["something_column"]....

     

    Using the DataSource.Select(..) method as suggested above would have meant an additional roundtrip to the database. There's already way tooo much going on on the form I'm working on.

     

    Hope this helps

    Thanks

    www.fuzzelogicSolutions.com

     

    • Proposed as answer by DavidTristan Friday, February 11, 2011 10:40 PM
    Wednesday, September 22, 2010 9:52 PM
  • Hi  

    It is possible to use the SQLDataSource control with text boxes and programicly use all the sql command in the SQL DataSource control

    The SQLDataSource control panel has a InsertQuery, UpdateQuery, DeleteQuery, and SelectQuery property which you can open up and use to create the SQL Statements, parameter statements and connect to text boes.

     <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:csEdNew %>"
            SelectCommand="SELECT [ClassName], [ClassDescription], [StartDate], [Instructor], [HtmlLink], [RecordID] FROM [NewClasses] WHERE ([RecordID] = ?)"
            DeleteCommand="DELETE FROM [NewClasses] WHERE [RecordID] = ?"
            InsertCommand="INSERT INTO [NewClasses] ([ClassName], [ClassDescription], [StartDate], [Instructor], [HtmlLink]) VALUES (?, ?, ?, ?, ?)"
            ProviderName="<%$ ConnectionStrings:csEdNew.ProviderName %>"
           
            UpdateCommand="UPDATE [NewClasses] SET [ClassName] = ?, [ClassDescription] = ?, [Instructor] = ?, [HtmlLink] = ? WHERE [RecordID] = ?"
            DataSourceMode="DataReader">
            <DeleteParameters>
                <asp:ControlParameter ControlID="txtRecordID" Name="RecordID" PropertyName="Text"
                    Type="Int32" />
            </DeleteParameters>
            <InsertParameters>
                <asp:ControlParameter ControlID="txtName" Name="ClassName" PropertyName="Text" Type="String" />
                <asp:ControlParameter ControlID="txtDescription" Name="ClassDescription" PropertyName="Text"
                    Type="String" />
                <asp:SessionParameter Name="StartDate" SessionField="StartDate" Type="DateTime" />
                <asp:ControlParameter ControlID="txtInstructor" Name="Instructor" PropertyName="Text"
                    Type="String" />
                <asp:ControlParameter ControlID="txtHtmlLink" Name="HtmlLink" PropertyName="Text"
                    Type="String" />
            </InsertParameters>
            <SelectParameters>
                <asp:ControlParameter ControlID="ddlClassNames" Name="?"
                    PropertyName="SelectedValue" />
            </SelectParameters>
            <UpdateParameters>
                <asp:ControlParameter ControlID="txtName" Name="ClassName" PropertyName="Text" Type="String" />
                <asp:ControlParameter ControlID="txtDescription" Name="ClassDescription" PropertyName="Text"
                    Type="String" />
                <asp:ControlParameter ControlID="txtInstructor" Name="Instructor" PropertyName="Text"
                    Type="String" />
                <asp:ControlParameter ControlID="txtHtmlLink" Name="HtmlLink" PropertyName="Text"
                    Type="String" />
                <asp:ControlParameter ControlID="txtRecordID" Name="RecordID" PropertyName="Text"
                    Type="Int32" />
            </UpdateParameters>
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:csEdNew %>"
            ProviderName="<%$ ConnectionStrings:csEdNew.ProviderName %>"
            SelectCommand="SELECT ClassName, RecordID, StartDate FROM NewClasses WHERE (StartDate > ?) ORDER BY ClassName">
            <SelectParameters>
                <asp:SessionParameter Name="TodysDate" SessionField="TodaysDate" Type="DateTime" />
            </SelectParameters>
        </asp:SqlDataSource>

     


    Partial Class HandEdit3
        Inherits System.Web.UI.Page

        Dim connectionString As String = WebConfigurationManager.ConnectionStrings("csEdNew").ConnectionString

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not IsPostBack Then
                Session("StartDate") = Today.AddDays(90).ToShortDateString
                Session("TodaysDate") = Today.ToShortDateString
            End If
        End Sub

        'Save New or Updae old record
        Protected Sub btnSave_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
            'If RecordID box is not empty then update current record
            'else Insert new record
            If txtRecordID.Text <> "" Then
                Try
                    Dim intRecAff As Integer = SqlDataSource1.Update()
                    If intRecAff = 1 Then
                        clearText()
                        ddlClassNames.DataBind()
                    End If

                Catch except As Exception
                    lblresults.Text = except.Message
                End Try
            Else
                Try
                    Dim intRecAff As Integer = SqlDataSource1.Insert()
                    If intRecAff = 1 Then
                        clearText()
                        ddlClassNames.DataBind()
                    End If
                Catch except As Exception
                    lblresults.Text = except.Message
                End Try
            End If
        End Sub

        Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
            If txtRecordID.Text <> "" Then
                Try
                    Dim intRecAff As Integer = SqlDataSource1.Delete()
                    If intRecAff >= 0 Then
                        clearText()
                        ddlClassNames.DataBind()
                    End If

                Catch ex As Exception
                    lblresults.Text = ex.Message
                End Try
            End If
        End Sub

    ' Now instead of using a ado command to be able to minipulate the data for the SQL Select statement as in the GetClassRecord  subroutine I use event handler "ddlClassNames_SelectedIndexChanged" uses a DirectCast statement

    Dim rdr As OleDbDataReader = DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), OleDbDataReader)
            rdr.Read()

       Sub GetClassRecord(ByVal thisRecord As String)
            Dim sqlthis As String = "SELECT [ClassName], [ClassDescription], [StartDate], [Instructor], [HtmlLink], [RecordID] FROM [NewClasses] WHERE ([RecordID] = ?)"
            Dim con As New OleDbConnection(connectionString)
            Dim cmd As New OleDbCommand(sqlthis, con)
            Dim rdr As OleDbDataReader
            cmd.Parameters.AddWithValue("@RecordID", thisRecord)
            Try
                con.Open()
                rdr = cmd.ExecuteReader()
                rdr.Read()
                txtRecordID.Text = rdr("RecordID")
                txtName.Text = rdr("ClassName")
                txtDescription.Text = rdr("ClassDescription")
                txtInstructor.Text = rdr("Instructor")
                txtHtmlLink.Text = rdr("HtmlLink")
                rdr.Close()
                btnDelete.Enabled = True
            Catch err As Exception
                lblresults.Text = "error finding record. "
                lblresults.Text &= err.Message
            Finally
                con.Close()
            End Try
        End Sub


        Protected Sub ddlClassNames_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlClassNames.SelectedIndexChanged
            'Dim thisRecord As String = ddlClassNames.SelectedItem.Value
            'GetClassRecord(thisRecord)
            Dim rdr As OleDbDataReader = DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), OleDbDataReader)
            rdr.Read()
            txtRecordID.Text = rdr("RecordID")
            txtName.Text = rdr("ClassName")
            txtDescription.Text = rdr("ClassDescription")
            txtInstructor.Text = rdr("Instructor")
            txtHtmlLink.Text = rdr("HtmlLink")
            rdr.Close()
            btnDelete.Enabled = True
        End Sub

        Sub clearText()
            txtName.Text = ""
            txtDescription.Text = ""
            txtInstructor.Text = ""
            txtRecordID.Text = ""
            txtHtmlLink.Text = ""
            lblresults.Text = ""
            btnDelete.Enabled = False
        End Sub

        Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
            clearText()
        End Sub

    End Class

    David

     

    Friday, February 11, 2011 10:51 PM
  • Just to confirm/expand on this OLD topic...

    I was doing something similar (I think) and this topic helped steer me in the right direction.

    In my case, I have a gridview & SQLDataSource declared in my ASPX page.  At first, it was only these two things in the equation, but I didn't "bind" them in the ASPX page.  A button elsewhere did a little bit of validation, then the following two things:

    gvFileHeaderInfo.DataSource = dsFileHeaderInfo;
    gvFileHeaderInfo.DataBind();
    

    My result set was always just 1 row and later I wanted to use one of the values elsewhere.  I remember having problems with this before... something about not being able to touch/read from the datasource directly after it was bound to a control.  Now I do the following to run the select command, pull the data into a DataView, then into a DataTable.  I guess this is making a copy of the data in-memory, but it's only running the query  once:

    DataView dvHeaderInfo = (DataView)dsFileHeaderInfo.Select(DataSourceSelectArguments.Empty);
    DataTable dtHeaderInfo = dvHeaderInfo.ToTable();
    
    lnkOriginalDBName.Text = dtHeaderInfo.Rows[0]["DatabaseName"].ToString();
    gvFileHeaderInfo.DataSource = dvHeaderInfo;
    gvFileHeaderInfo.DataBind();
    
    If I bound the gridview to the datasource (like in the first example), it still works, BUT it runs the query twice.
    • Proposed as answer by DavidTristan Thursday, March 15, 2012 8:43 PM
    Wednesday, March 23, 2011 11:10 PM
  • Here is an answer to the original qustion

    It uses a DirctCast function to extract the ado DataReader  or Data set object out of the SQLDataSource control

    Bind Data From a SqlDataSource to a Label
    http://www.mikesdotnetting.com/Article/64/Bind-Data-From-a-SqlDataSource-to-a-Label

    David

    Thursday, March 15, 2012 8:49 PM
  • David,

    This thread certainly seems like the answer to my question(s), but I am missing some knowledge of the syntax.  For example, "DataView view=(DataView)dataSource.Select(args);".  Where do I find an exposition of this statement and others like it?  Is it in some VB manual?  Is it VB? Please forgive my lack of knowledge in what must be routine discussion, but I need a boost.

    Thanx in advance.

    eps123

    
    

    eps123

    Monday, December 31, 2012 10:40 PM
  • Hi,

    Did you see this blog post http://msmvps.com/blogs/egoldin/archive/2006/12/27/how-to-get-datatable-out-of-sqldatasource.aspx



    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog

    Monday, December 31, 2012 11:49 PM