0

I'm trying to translate between php and ASP.Net. In php I can connect to the database, run a query, and print out the results in html tags as shown below:

$query="SELECT * FROM comments;";

$result=$mysqli->query($query);

while($row=$result->fetch_object()) {
    echo "<div class=\"comment\">";
    echo "<h1>".$row->title."</h1>";
    echo "<p>".$row->comment."</p>";
    echo "</div>";
} 

?>

In ASP.NET with c#, how would I do this?

I'm aware I have to use SqlConnection() and SqlCommand() and possibly SqlDataReader(). But how do I make ASP.NET do what I have php doing above? And where do I place the code? In the Page Load method? Or in the middle of the html?

I have looked a using grid views and table views to pull data from the database, however they don't allow me to make the page look how I want. I want data from the database to populate a html template I mark up, not some predefined grid or table structure.

Thanks

1

1 Answer 1

1

I guess you could do all of this in sql-server as well. see below ....

Test Data

DECLARE @Comments TABLE(Title NVARCHAR(100), Comment NVARCHAR(4000))
INSERT INTO @Comments VALUES
('Title 1', 'Comments for under tile 1'),
('Title 2', 'Comments for under tile 2'),
('Title 3', 'Comments for under tile 3')

Query

SELECT 'comment'  AS [@class] 
       ,Title     AS [h1]
       ,Comment   AS [p]
FROM @Comments
FOR XML PATH('div');

Result

<div class="comment">
  <h1>Title 1</h1>
  <p>Comments for under tile 1</p>
</div>
<div class="comment">
  <h1>Title 2</h1>
  <p>Comments for under tile 2</p>
</div>
<div class="comment">
  <h1>Title 3</h1>
  <p>Comments for under tile 3</p>
</div>
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.