ScottieB
ScottieB

Reputation: 4052

Grab query results from SqlDataSource and store as string

I have a SQL query that will result in one string. Rather than bind a gridview, listview, etc to it and have a single lonely label inside, I just want to store the string (it'll eventually get used later elsewhere). For the life of me I cannot figure this out.

<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$      ConnectionStrings:ConnectionString %>"
SelectCommand="select [title] from [books]
               where([Genre]=@Genre)
OnSelected="SqlDataSource3_Selected">
<SelectParameters>
            <asp:Parameter Name="Title" Direction="ReturnValue" Type="String" />
            <asp:ControlParameter ControlID="DropDownList1" Name="genre" 
                PropertyName="SelectedValue" />

        </SelectParameters>

    </asp:SqlDataSource>

protected void SqlDataSource3_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
    string sqlreturnString = Convert.ToString(e.Command.Parameters["@Title"].Value);
    Label3.Text = sqlreturnString;
}

All this does is spit out '0' when I want it to display the title. If I change ["@Title"] to [1], it'll display the Genre. Right now there are only four books, each with a unique genre.

Upvotes: 0

Views: 6121

Answers (2)

Michael G. Workman
Michael G. Workman

Reputation: 375

I encountered this same issue also when doing C# and ASP.NET, it would be really nice to have a method that dumps out a string of the text results of the query in a SQLDataSource or an AccessDatasource. Until then, Here is an example of the solution I found that works very well:

AccessDataSource MyDataSource = new AccessDataSource("~/App_Data/MyDB.mdb",
                                                                "SELECT Name FROM Employees");
DataView MyView = (DataView) MyDataSource.Select(DataSourceSelectArguments.Empty);
lblResults.Text = MyView[0][1].ToString();

This example will also work with SqlDataSource objects.

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94645

Add a button and write this code in the handler of button's click.

DataSourceSelectArguments sr = new DataSourceSelectArguments();
DataView  dv =(DataView) SqlDataSource3.Select(sr);
if(dv.Count!=0)
   Label1.Text = dv[0][0].ToString();

Upvotes: 2

Related Questions