I’m having trouble creating a table and putting data pulled from SQL into it. My solution at the moment is to create a table in Default.aspx, and then create the rows and cells in the C# code.
My aspx code:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Select a topic to view.
</h2>
<asp:Table ID="solutions" runat="server" Width="100%">
</asp:Table>
</asp:Content>
And where all the action should, but doesn’t happen:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HtmlAgilityPack;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection anca = new System.Data.SqlClient.SqlConnection();
anca.ConnectionString = "Data Source=anca;Initial Catalog=servicedesk;
anca.Open();
SqlCommand sub = new SqlCommand("SELECT TITLE FROM dbo.Solution", anca);
SqlDataReader sReader = sub.ExecuteReader();
List<String> subject = new List<string>();
int solCount = 0;
while (sReader.Read())
{
subject.Add(sReader.ToString());
solCount++;
}
sReader.Close();
TableRow newRow = new TableRow();
TableCell newcell = new TableCell();
int adder = 0;
while (adder <= solCount)
{
solutions.Rows.Add(newRow);
for (int i = 0; i <= 6; i++)
{
newRow.Cells.Add(newcell);
newcell.Text = subject[adder].ToString();
}
}
}
}
}
Obviously I’m a bit green with it all. Basically what happens is it pulls all of the solution titles from a database and I want the titles to each be in a cell of their own, where I will go on to link them to the respective pages. Hopefully it all makes sense, if not I am happy to provide more information.
First you are adding empty row to table and then filling the row with content. You should add the row after its filled with cell content (i.e. after the loop not before). Also if I am not seeing it wrong, you are not increasing “adder” each loop so it should fall into infinite loop. Also seems like you are pulling only title from DB…so I don’t know why you were trying to add 7 columns/cells each row. By the way posting this from office so let me know if I did anything wrong and I will fix it asap :).
I think a more elegant way will be using ListView or Repeater control rather than dynamically generating the table like that.