我有以下代码,它将行数跨度添加到html字符串中的数据表中,但我希望它不作为参数接收数据表,而是接收作为参数接收C#中的html字符串。
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Subject");
dt.Columns.Add("Code");
dt.Columns.Add("Test");
dt.Columns.Add("Class");
dt.Rows.Add("Math", "9", "ABC", "D1");
dt.Rows.Add("Math", "9", "ABD", "D2");
dt.Rows.Add("Math", "9", "ABE", "D3");
dt.Rows.Add("Math", "9", "ABF", "D4");
dt.Rows.Add("Science", "91", "ABG", "D1");
dt.Rows.Add("Science", "91", "ABH", "D2");
dt.Rows.Add("Science", "91", "ABI", "D3");
dt.Rows.Add("English", "191", "ABJ", "D1");
Label1.Text = ConvertDataTableToHTML(dt);
}
public static string ConvertDataTableToHTML(DataTable dt)
{
string html = "<table border=1>";
//add header row
html += "<tr>";
for (int i = 0; i < dt.Columns.Count; i++)
{
html += "<td>" + dt.Columns[i].ColumnName + "</td>";
}
html += "</tr>";
//add rows
string sub = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
html += "<tr>";
int count = dt.Select("Subject ='" + dt.Rows[i][0].ToString() + "'").Count();
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < 2)
{
if (sub != dt.Rows[i][0].ToString())
{
html += "<td rowspan='" + count + "'>" + dt.Rows[i][j].ToString() + "</td>";
}
continue;
}
html += "<td>" + dt.Rows[i][j].ToString() + "</td>";
}
sub = dt.Rows[i][0].ToString();
html += "</tr>";
}
html += "</table>";
return html;
}
这是我希望的结果
答案 0 :(得分:0)
代码有一些问题,以及一些改进代码的方法:
<table border=1>
缺少1
周围的引号。它应该是<table border='1'>
。<thead>
和<tbody>
标记。+=
,而是使用StringBuilder
。for
循环更改为foreach
循环。您的代码应更改为以下内容:
public static string ConvertDataTableToHTML(DataTable dt)
{
StringBuilder builder = new StringBuilder();
//add header row
builder.Append("<table border='1'><thead><tr>");
foreach (DataColumn col in dt.Columns)
{
builder.Append("<td>");
builder.Append(col.ColumnName);
builder.Append("</td>");
}
builder.Append("</tr></thead><tbody>");
//add rows
string sub = "";
...
builder.Append("</tbody></table>");
return builder.ToString();
}
(只需将相同的概念应用于我删除的中间代码。)