Hi Donny17,
I have created sample for your reference. You need to change you code as per the sample.
I have below record in the database table.
CustomerId |
Name |
Country |
1 |
Mudassar Khan |
India |
2 |
Maria |
Austria |
3 |
Ana Trujillo |
France |
4 |
Antonio Moreno |
Brazil |
5 |
Christina Berglund |
Ireland |
You need to add a Label or Literal control to page inorder to display the html content from database table.
HTML
<asp:Label ID="lblTable" runat="server" />
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 5 CustomerId,Name,Country FROM Customers", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.Text;
sda.Fill(dt);
}
}
}
string htmlTable = "<table border='1' cellpadding='0' cellspacing='0'><tr>";
foreach (DataColumn column in dt.Columns)
{
htmlTable += "<th>" + column.ColumnName + "</th>";
}
htmlTable += "</tr>";
foreach (DataRow dr in dt.Rows)
{
string id = dr["CustomerId"].ToString();
string name = dr["Name"].ToString();
string country = dr["Country"].ToString();
htmlTable += "<tr><td>" + id + "</td><td>" + name + "</td><td>" + country + "</td></tr>";
}
htmlTable += "</table>";
lblTable.Text = htmlTable;
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim dt As DataTable = New DataTable()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT TOP 5 CustomerId,Name,Country FROM Customers", con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
cmd.CommandType = CommandType.Text
sda.Fill(dt)
End Using
End Using
End Using
Dim htmlTable As String = "<table border='1' cellpadding='0' cellspacing='0'><tr>"
For Each column As DataColumn In dt.Columns
htmlTable += "<th>" & column.ColumnName & "</th>"
Next
htmlTable += "</tr>"
For Each dr As DataRow In dt.Rows
Dim id As String = dr("CustomerId").ToString()
Dim name As String = dr("Name").ToString()
Dim country As String = dr("Country").ToString()
htmlTable += "<tr><td>" & id & "</td><td>" & name & "</td><td>" & country & "</td></tr>"
Next
htmlTable += "</table>"
lblTable.Text = htmlTable
End If
End Sub
Screenshot
