1

In asp.net, I want to select the Top x from a sql server database where x is set programattically in the code behind (cs).

Data binding a string from the code behind to pass to the SelectCommand in the SqlDataSource control doesn't seem to be working.

Is there a way to bind a variable from the code to the SelectCommand of the aspx SqlDataSource, or is there another way?

2
  • You could do this, making the databind without using a SqlDataSource. You could do so in your code behind class. Initially, I suggest you try to find out how we can open a sql connection, query a table and consume the result, ADO.NET. Then using a parameter to your query string, you could achieve so fairly easily. Commented Apr 20, 2015 at 16:51
  • Is your select command a stored procedure or hard coded in your asp.net code? What version of sql server are you working with? Commented Apr 20, 2015 at 17:19

5 Answers 5

2

Assuming you have a SQL data source declared in the front end.

<asp:SqlDataSource ID="SqlDataSource" runat="server">
</asp:SqlDataSource>

In the code behind of your page add to the appropriate event code something like this to programmatically set the SQL data source command.

string sTop = "10";
SqlDataSource.SelectCommand = "SELECT Top " + sTop + " * FROM dbo.clients";

Also, consider using a DataTable or DataSet instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. This is exactly what I needed to know about getting a string to be used as the SelectCommand in the SqlDataControl. I did find another solution on MSDN using SessionState (see my own answer to the question.) Thank you very much for your time!
2

you can do this:

  begin 
      declare @top int 
      set @top = 2  
      SELECT top(@top) *  FROM MyTable
  end

EDIT Since you can use a variable with TOP you can send the paramater "@top"(int type) and use it like the above sql-code (only the select)...But your question already has been answered (see last answer).

4 Comments

Mind to explain your solution a bit?
@ZoharPeled No. that is valid code (at least mssql 2008, i don´t have other version to test).
@MarkusWMahlberg since you can use a variable with TOP then you can pass a parameter to your query (or stored procedure). I'll edit my answer.
@AiApaec please add this to your answer using the edit button. ;)
1

Thanks to all. I learned a lot! After posting the question, I found these links in MSDN that showed me how to use SessionState and... the missing link... Parameters! I learned how to put them in the SqlDataControl for the SelectCommand to use.

https://msdn.microsoft.com/en-us/library/xt50s8kz(v=vs.140).aspx

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sessionparameter(v=vs.140).aspx

My code-behind:

int count = 5;
Session["itemCount"] = count;

my apsx:

<SqlDataSource>
    ...
    SelectCommand="SELECT TOP (@itemMax) * FROM TableName">

    <SelectParameters>
        <asp:SessionParameter Name="itemMax" SessionField="itemCount"/>
    </SelectParameters>
</SqlDataSource>

Again, thanks to all. It was much appreciated and made my first forray into the Stack Overflow community a positive experience!

3 Comments

Well it was being positive, until my question got voted down. Ouch! I'm still pretty new at all this, so I did what research I could, and asked as clear as my knowledge would allow. Oh well. Back to work. And by the way, thanks for the constructive criticism. I'll try to do better next time.
Dont be discouraged by a downvote. Things happen. Your question and the answers here helped me a lot today.
Thanks for the encouragement!
0

This is another way of solving your problem:

        string cmdStr1 = "SELECT * FROM [Table1];";
        DataSet ds = new DataSet();
        try
        {
            using (SqlConnection conn1 = new SqlConnection(connStr))
            {
                using (SqlCommand cmd1 = new SqlCommand(cmdStr1, conn1))
                {
                    conn1.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd1))
                    {
                        da.Fill(ds);
                        GridView1.DataSource = ds;
                        GridView1.DataBind();
                    }
                    conn1.Close();
                    cmd1.Dispose();
                    conn1.Dispose();
                }
            }
        }
        catch (Exception ex)
        {
            Label2.Text = ex.ToString();

1 Comment

How would that solve the Limit/Top part of the question?
0

You could use row_number() if you want to parameterize the number of rows to be selected.

SELECT * FROM (

SELECT ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber, column1, column2,column3 FROM tablename ) AS t

WHERE rownumber <= @topCount

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.