rai nalasa rai nalasa - 2 months ago 6
ASP.NET (C#) Question

load each table data to html table using label

How do I load each data on my sql server to label?
So far I could only load 1 data.I can't load all of them I can't figure out how to start.
Here is the list of data I want to load.

enter image description here

My current output: enter image description here

This is my code:

private string product_name { get; set; }
private string product_type { get; set; }
private string image_desc { get; set; }

private void load_products()
{
con.Open();
cmd = new SqlCommand(@"SELECT productName,productType,image_desc
FROM Products3",con);

rdr = cmd.ExecuteReader();

if(rdr.Read())
{
while (rdr.Read())
{
product_name = rdr["productName"].ToString();
product_type = rdr["productType"].ToString();
image_desc = rdr["image_desc"].ToString();

// foreach()
lbl_table.Text = @"<table class='table table-bordered'>
<thead>
<tr>
<th>Product Name</th>
<th>Product Type</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td>"+product_name+@"</td>
<td>"+product_type+@"</td>
<td>"+image_desc+@"</td>
</tr>
</tbody>
</table>";
}
}
con.Close();
}


How could I get all the table data?I figured I need some
foreach
but I don't know where to use it.I wanted to create seperate table for each product.

Answer

Define Label text before the while loop like this

lbl_table.Text = @"<table class='table table-bordered'>
                               <thead>
                               <tr>
                               <th>Product Name</th>
                               <th>Product Type</th>
                               <th>Image</th>
                               </tr>
                               </thead>
                               <tbody>";

Now inside the while loop you need to create only new row for each record like this

While()
{
      ...
      lbl_table.Text += @"<tr>
      <td>"+product_name+@"</td>
      <td>"+product_type+@"</td>
      <td>"+image_desc+@"</td>
      </tr>";
}

After completing while loop add tags for closing Table

lbl_table.Text += @"</tbody></table>";

Thats it.

Comments