Show data in ASP.NET html table

Basically use the classic ASP\PHP\Spaghetti code approach.

First of all, place your code in one public method that returns a string. The method:

public string getWhileLoopData()
{
        string htmlStr = "";
        SqlConnection thisConnection = new SqlConnection(dbConnection);
        SqlCommand thisCommand = thisConnection.CreateCommand();
        thisCommand.CommandText = "SELECT * from Test";
        thisConnection.Open();
        SqlDataReader reader = thisCommand.ExecuteReader();

        while (reader.Read())
        {
            int id = reader.GetInt32(0);
            string Name = reader.GetString(1);
            string Pass = reader.GetString(2);
            htmlStr +="<tr><td>"+id+"</td><td>"+Name+"</td><td>"+Pass+"</td></tr>"                   
        }

        thisConnection.Close();
        return htmlStr;
}

Then you can use the <%=getWhileLoopData()%> tag in ASP.NET that is equal to <%Response.Write(getWhileData())%>

It should look something like this:

<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/test.master" CodeFile="test.aspx.cs" Inherits="test" %>

<asp:Content ID="BodyContent" runat="server"  ContentPlaceHolderID="ContentPlaceHolder">
    <table width="100%" align="center" cellpadding="2" cellspacing="2" border="0" bgcolor="#EAEAEA" >
        <tr align="left" style="background-color:#004080;color:White;" >
            <td> ID </td>                        
            <td> Name </td>            
            <td>Pass</td>                        
        </tr>

        <%=getWhileLoopData()%>

    </table>
</asp:Content>

There is also the option to use an repeater control and bind the data from your DB to an Item Template of your liking.


I suggest you to use repeater control and create your html table structure in repeater.

<table cellpadding="0" cellspacing="0" width="100%">
<asp:Repeater ID="rpt" runat="server" >
<HeaderTemplate>
<tr class="Header">
<td>
ID
</td>
<td>
Name
</td>
<td>
Pass
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("ID")%>
</td>
<td>
<%# Eval("Name")%>
</td>
<td>
<%# Eval("Pass")%>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>

bind repeater as same as you bind gridview

thanks

Tags:

C#

Html

Asp.Net