有没有办法在不知道字段名称的情况下显示ListView?在后面的代码中,我将数据传递给ListView,但不知道如何显示它,因为我打算将这个模板用于我的所有表。
在模板中
<tr>
foreach( Key in ListView.Keys )
{
<th>Key</th>
}
</tr>
foreach( Row in LisView.Rows )
{
<tr>
foreach ( Column in Row )
<td>Column</td>
</tr>
}
输出示例:
----------------------------
| id | name | surname |
----------------------------
| 1 | John | Doe |
| 2 | Jack | Jones |
| 3 | Mary | Williams |
| 4 | Sue | Smith |
任何帮助表示赞赏!提前谢谢!
答案 0 :(得分:0)
这解决了我的问题:
HTML
<asp:PlaceHolder ID = "PlaceHolder1" runat="server" />
命名空间
using System.Data;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
代码
//Populating a DataTable from database.
DataTable dt = this.GetData();
//Building an HTML string.
StringBuilder html = new StringBuilder();
//Table start.
html.Append("<table border = '1'>");
//Building the Header row.
html.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
html.Append("<th>");
html.Append(column.ColumnName);
html.Append("</th>");
}
html.Append("</tr>");
//Building the Data rows.
foreach (DataRow row in dt.Rows)
{
html.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
html.Append("</td>");
}
html.Append("</tr>");
}
//Table end.
html.Append("</table>");
//Append the HTML string to Placeholder.
PlaceHolder1.Controls.Add(new Literal { Text = html.ToString() });
答案 1 :(得分:0)
找到更好的方法:
HTML
<asp:Table ID="testTable" runat="server" />
代码
TableRow tHeaderRow = new TableHeaderRow();
tHeaderRow.TableSection = TableRowSection.TableHeader;
testTable.Rows.Add(tHeaderRow);
foreach (DataColumn column in all("Users").Columns)
{
TableHeaderCell tHeaderCell = new TableHeaderCell();
tHeaderCell.Text = column.ColumnName;
tHeaderRow.Cells.Add(tHeaderCell);
}
foreach( DataRow row in all("Users").Rows)
{
TableRow tRow = new TableRow();
testTable.Rows.Add(tRow);
foreach (DataColumn column in all("Users").Columns)
{
TableCell tCell = new TableCell();
tCell.Text = row[column.ColumnName].ToString();
tRow.Cells.Add(tCell);
}
}
我的all("Users")
函数返回DataTable