我正在使用for循环迭代我的数据集中的行,并将其打印到屏幕上,但我想知道如何用css包装值?我用来动态创建表的代码是
test.GetSubjects();
int subjectid = 0;
// Current row count.
int rowCtr;// = 0;
// Total number of cells per row (columns).
int cellCtr;
// Current cell counter.
int cellCnt;
//count number of rows in dataset
int rN = test.dsSubjects.Tables[0].Rows.Count;
cellCnt = 3;
for (rowCtr = 1; rowCtr <= rN; rowCtr++)
{
// Create a new row and add it to the table.
TableRow tRow = new TableRow();
Table1.Rows.Add(tRow);
for (cellCtr = 1; cellCtr <= 3; cellCtr++)
{
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
/* If the rowcounter is equal to the record numbers
* then it has to break because if not it will throw an error
* saying that there is no row at ending position */
if (rowCtr == rN)
break;
string myStr = test.dsSubjects.Tables[0].Rows[rowCtr -1]["SubjectName"].ToString();
tCell.Controls.Add(new LiteralControl(myStr));
tRow.Cells.Add(tCell);
rowCtr++;
/* If the cellcount is 3 then it needs to break, if not then
* you'll miss every 4rth record, don't know why. But this works */
if (cellCtr == 3)
{
rowCtr = rowCtr - 1;
break;
}
}
}
并且我需要在css中包装每个值,这是我想用来包装每个值的css
border-style: solid;
border: 1px solid lightblue;
width: 58px;
height: 27px;
border-radius: 5px;
background-color:lightblue;
原因是我将值转换为链接并希望为其添加样式。我想我可以将样式添加到正在生成的单元格中,但由于我在后面的代码中执行了此操作,因此我不知道如何执行此操作。
答案 0 :(得分:1)
将HTML格式添加到myStr对象中 string myStr =“”+ test.dsSubjects.Tables [0] .Rows [rowCtr -1] [“SubjectName”]。ToString()+“”;例如。
答案 1 :(得分:1)
而不是仅将文本输出为
string myStr = test.dsSubjects.Tables[0].Rows[rowCtr -1]["SubjectName"].ToString();
tCell.Controls.Add(new LiteralControl(myStr));
您可以实例化span对象,将该类添加到span对象的class属性中,然后将span对象添加到单元控件集合中。
var span = new HtmlGenericControl("span");
span.InnerHtml = test.dsSubjects.Tables[0].Rows[rowCtr -1]["SubjectName"].ToString();
span.Attributes["class"] = "myCssClass";
tCell.Controls.Add(span);
答案 2 :(得分:1)
鉴于您使用的是ASP.NET,我强烈建议您使用Razor引擎(如果可以使用它)。目前你正在艰难地做这件事。
以下是Razor的外观示例,假设您确实需要将每个值包装在DIV中:
<table>
@foreach(DataRow row in test.dsSubjects.Rows)
{
<tr>
<td><div class="myCssClass">@row["Field1"]</div></td>
<td><div class="myCssClass">@row["Field2"]</div></td>
<td><div class="myCssClass">@row["Field3"]</div></td>
</tr>
}
</table>
它确实简化了很多事情。