[英]HTML generate rowspan in html table string
I have the following code, which adds rowspan to a datatable in an html string, but I want it not to receive as a parameter a datatable, but instead to receive as a parameter an html string in C#. 我有以下代码,该代码将rowpan添加到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;
}
This is the result that I hope 我希望这是结果
There are a few things wrong with the code, and a few ways you can improve your code: 该代码有一些问题,还有一些改进代码的方法:
<table border=1>
is missing the quotes around the 1
. <table border=1>
缺少1
周围的引号。 It should be <table border='1'>
. 它应该是<table border='1'>
。 <thead>
and <tbody>
tags around the row tags. 您在行标记周围缺少<thead>
和<tbody>
标记。 +=
, use a StringBuilder
. 而不是经常使用+=
,而是使用StringBuilder
。 for
loops to foreach
loops. 为了使代码更整洁,您可以将一些for
循环更改为foreach
循环。 Your code should be changed to something like this: 您的代码应更改为以下内容:
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();
}
(Just apply the same concepts to the middle code that I removed.) (只需将相同的概念应用于我删除的中间代码即可。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.