2

I am trying to display the count of a table from my database. I have a function that returns the count of the rows. I'm new to c# and I'm not sure how to call the function in my html so that it displays the returned value.

Here's my c# function that I got from How to count the number of rows from sql table in c#?:

public int Get_Count(object sender, EventArgs e)
{
    {
        string stmt = "SELECT COUNT(*) FROM dbo.listing";
        int count = 0;

        using (SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
        {
            using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
            {
                thisConnection.Open();
                count = (int)cmdCount.ExecuteScalar();
            }
        }
        return count;
    }
} 

And here's the HTML line that I would like to display the returned count:

<p class="lead text-muted block text-center"><strong>Get_Count()</strong> results found</p>
3
  • 1
    Is this MVC or WebForms? Commented Dec 8, 2017 at 0:13
  • I am using WebForms Commented Dec 8, 2017 at 1:58
  • Is there an Web API / WCF service that your WebForms app is calling or is this through a DAL interface (assembly that the app is using). Commented Dec 8, 2017 at 2:20

1 Answer 1

5

in page load event

     protected void Page_Load(object sender, EventArgs e)
    {
        this.DataBind();
    }

    public int Get_Count()
   {
      {
          string stmt = "SELECT COUNT(*) FROM dbo.listing";
          int count = 0;

          using (SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
            {
               using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
                 {
                    thisConnection.Open();
                    count = (int)cmdCount.ExecuteScalar();
                 }
           }
          return count;
       }
    }

then

    <p class="lead text-muted block text-center"><strong><%# Get_Count() %></strong> results found</p>
Sign up to request clarification or add additional context in comments.

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.