c# - 使用 C# 为表格单元格添加颜色

标签 c# .net asp.net html

我正在创建一个表格并通过 c sharp 代码添加包含内容的单元格。我的代码如下:

//creating the table
Table table1 = new Table();
table1.ID = "table1";
table1.BorderStyle = BorderStyle.Dashed;
table1.GridLines = GridLines.Both;
this.Controls.Add(table1);

//adding first row
TableRow row1 = new TableRow();

//adding first cell
TableCell cell1 = new TableCell();

//adding label
Label text1 = new Label();
text1.Text = "Sourav Ganguly";

cell1.Controls.Add(text1);
row1.Controls.Add(cell1);
table1.Controls.Add(row1);

//adding second cell
TableCell cell2 = new TableCell();

//adding label
Label text2 = new Label();
text2.Text = "Rahul Dravid";

cell2.Controls.Add(text2);
row1.Controls.Add(cell2);

//adding third cell
TableCell cell3 = new TableCell();

//adding label
Label text3 = new Label();
text3.Text = "Sachin Tendulkar";

cell3.Controls.Add(text3);
row1.Controls.Add(cell3);

//adding second row
TableRow row2=new TableRow();

//adding first cell
TableCell cell4 = new TableCell();

//adding label
Label text4 = new Label();
text4.Text = "Virender Shewag";

cell4.Controls.Add(text4);
row2.Controls.Add(cell4);
table1.Controls.Add(row2);

//adding second cell
TableCell cell5 = new TableCell();

//adding label
Label text5 = new Label();
text5.Text = "MS Dhoni";

cell5.Controls.Add(text5);
row2.Controls.Add(cell5);
table1.Controls.Add(row2);

//adding third cell
TableCell cell6 = new TableCell();

//adding label
Label text6 = new Label();
text6.Text = "Zaheer Khan";

cell6.Controls.Add(text6);
row2.Controls.Add(cell6);
table1.Controls.Add(row2);

我想为每个单元格添加背景颜色。是否有可能创建这样的东西?即在第一行的第一个单元格中,我希望仅将红色添加到大约 50% 的单元格中。我希望单元格在剩余的 50% 中保持无色(通常为白色)。同样,对于第一行的第二个单元格,我希望为 80% 的单元格添加黄色,我希望其余 20% 的单元格为默认的白色。是否有可能使用 C# 实现此类功能?

最佳答案

不完全是,但您可以尝试通过将 Text 属性设置为以下来复制该行为:

<div style="width:100px;height:20px">
  <div style="background-color:red;width:80%;height:20px"/>
  <div style="float:left">Hello</div>
</div>

当然,您会想要替换硬编码的尺寸和颜色。

关于c# - 使用 C# 为表格单元格添加颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6772513/

相关文章:

c# - Entity Framework 使用 IdentityDbContext 和代码优先自动迁移表位置和模式?

c# - 为什么具有 T : class result in boxing? 约束的泛型方法

c# - 我需要使用继承来实现 C# 深拷贝构造函数。有哪些图案可供选择?

c# - 如何从 WCF asmx C# 获取客户端的计算机名称?

c# mvc 将请求重新路由到不同的服务器

.net - web 的意思是无状态的,而 http 是无状态协议(protocol)?

带有队列或列​​表的 C# 流畅接口(interface)

c# - T?,C# 9 中的可为空类型参数

c# - 从 .NET Core 调用 VISA API 时出错

c# - 使用 Moq 模拟方法的某些部分