0

I tried searching for this, but I can't find an answer that works. All I need to do is find a way to display SQL data from a simple query onto an aspx page. I'm using C# to connect to the database. I have not trouble posting to the database. My code seems correct. I'm not getting any errors, however, the web page doesn't display anything.

Here is the code on the C# file:

public int GetResults( )
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data"].ConnectionString); 
    SqlCommand cmd = new SqlCommand("select count (ColumnA) from TableA",conn);
    cmd.CommandType = CommandType.Text;

    conn.Open();
    int Rslt= (Int32)cmd.ExecuteNonQuery();
    return (Rslt);
}

And here is the aspx page:

<div class="lc">      
  the results are=  <%GetResults();%>
</div> 

1 Answer 1

1

You should use ExecuteScalar() rather like

int Rslt= (int)cmd.ExecuteScalar();

Again, the calling doesn't looks correct. It rather should be

<%# GetResults() %>

As @Jacob pointed: <% %> is for executing a code block; whereas <%= %> or <%# %> is for outputting content.

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

3 Comments

To explain the last part, <% %> is for executing a code block; <%= %> or <%# %> is for outputting content.
But I'd use <%: GetResults() %> to automatically HTML-encode the output.
Thank you, Jacob! The <%: GetResults() %> worked.

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.