gpt4 book ai didi

c# - 如何根据单元格值使用颜色设置 Asp.net GridView 单元格的样式

转载 作者:行者123 更新时间:2023-11-30 14:12:05 27 4
gpt4 key购买 nike

我有一个 Gridview ,它有一个名为 student_Class 的列。 GridView 上大约有 80 个类。我使用 GroupBy 查询对此类进行了分组。

现在我想用不同的颜色为这个不同的类设置样式。怎么可能?
RowDataBound 上编写所有类并赋予颜色并不容易。

还有其他办法吗?

代码:

groups = (ArrayList)Session["selectedclass"];
SELECT id,name,student_Class FROM student where
student_Class='"+groups[0].ToString().Trim()+"'
group by student_Class.

给出数据为

 id   name   student_class
1 aa A
2 bb A
3 cc A
4 dd B
5 ee B
6 as B
7 ss B
8 AZZ D

值为A 的学生类需要相同的颜色(单元格),B 需要其他颜色,等等。

最佳答案

ASPX:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
DataKeyNames="id" DataSourceID="SqlDataSource1"
ondatabound="GridView1_DataBound" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="id" HeaderText="id" ReadOnly="True"
SortExpression="id" />
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="student_class" HeaderText="student_class"
SortExpression="student_class" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SiteConnectionString %>"
SelectCommand="SELECT * FROM [student]">
</asp:SqlDataSource>

代码隐藏:

static string[,] ClassNames =
{
{"A","Red"},
{"B","Blue"},
{"C","Pink"},
{"D","Green"},
// and so on
};
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string className = e.Row.Cells[2].Text;
string color = "Black";
for (int i = 0; i <= ClassNames.GetUpperBound(0); i++)
{
if (ClassNames[i, 0] == className)
{
color = ClassNames[i, 1];
e.Row.Cells[2].ForeColor = Color.FromName(color);
e.Row.Cells[2].BorderColor = Color.Black;
break;
}
}
}

enter image description here

关于c# - 如何根据单元格值使用颜色设置 Asp.net GridView 单元格的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18670189/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com