Reputation: 299
I have this HTML table:
<table ID="tbl_ClientSearch" style="width: 83%;" runat="server">
<thead>
<tr>
<td>Client Account Number</td>
<td>Client Name</td>
</tr>
</thead>
<tbody>
<tr>
<td><asp:Literal ID="CliNox" runat="server"></asp:Literal></td>
<td><asp:Literal ID="CliNamex" runat="server"></asp:Literal></td>
</tr>
</tbody>
</table>
Then I have this query:
SqlCommand command = new SqlCommand(@"EXEC [dbo].[CTLC_SearchClient] '" + SearchVal + "';");
SqlConnection conn = new SqlConnection(connString);
conn.Open();
command.Connection = conn;
SqlDataReader readers = command.ExecuteReader();
if (readers.HasRows)
{
while (readers.Read())
{
string CliNo = readers.GetString(0);
string CliName = readers.GetString(1);
CliNox.Text = string.Format("<a href='ClientInfo.aspx?ClientNumber={0}'>{0}</a>", CliNo.ToString());
CliNamex.Text = CliName.ToString();
}
conn.Close();
}
This works but when I need to return multiple rows, this only returns 1 row since I only declared 1 for the table body. How can I solve this? Thank you in advance.
Upvotes: 1
Views: 1507
Reputation: 192
In Aspx page add placeholder apart from table like below.
<asp:PlaceHolder ID = "tableClientSearch" runat="server"/>
In Aspx.cs file.
StringBuilder html = new StringBuilder();
html.Append("<table border = '1'><thead><tr><td>Client Account
Number</td><td>Client Name</td></tr></thead>");
SqlCommand command = new SqlCommand(@"EXEC [dbo].[CTLC_SearchClient] '" + SearchVal + "';");
SqlConnection conn = new SqlConnection(connString);
conn.Open();
command.Connection = conn;
SqlDataReader readers = command.ExecuteReader();
if (readers.HasRows)
{
while (readers.Read())
{
html.Append("<tr>");
html.Append("<td>");
html.AppendFormat("<a href='ClientInfo.aspx?ClientNumber={0}'>{0}</a>", readers.GetString(0));
html.Append("</td>");
html.Append("<td>");
html.Append(readers.GetString(1));
html.Append("</td>");
html.Append("</tr>");
}
conn.Close();
}
html.Append("</table>");
tableClientSearch.Controls.Add(new Literal { Text = html.ToString() });
Upvotes: 1
Reputation: 7490
Delcare a protected table in aspx.cs file at class level
protected DataTable dt = new DataTable()
Fill this data table from sql query (by using DataAdapter), I guess you know how to do that, or just google it.
In aspx, replace
<tr>
<td><asp:Literal ID="CliNox" runat="server"></asp:Literal></td>
<td><asp:Literal ID="CliNamex" runat="server"></asp:Literal></td>
</tr>
by
foreach (DataRow dr in dt)
{
<tr>
<td><%= dr["columnName1"] %></td>
<td><%= dr["columnName2"] %></td>
</tr>
}
Upvotes: 1
Reputation: 1
I am not familiar with asp.net, however this situation looks similar to some that could occur in php, in which case I would try generating the entire table in asp. something along the lines of,
for row in tables
append to html <tr><td>data</td><td>moredata</td></tr>
insert html into <table></table>
Upvotes: 0