datalist在多个单元格上更改背景颜色

时间:2015-09-06 08:42:36

标签: c# asp.net datalist

我想更改每个datalist单元格的背景颜色。但我只能改变一种颜色......就像这样... enter image description here

我想在selectedIndex Changed ...

上实现这个逻辑
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
    foreach (DataListItem dli in DataList1.Items)
    {
        //if cell is not red make it red
        DataList1.SelectedItem.BackColor = Color.Red;

        //else cell is red .. make it blue(unselect)
    }        
}

如何实现切换功能?

1 个答案:

答案 0 :(得分:0)

创建两个静态辅助字段,用于定义默认颜色和所选颜色,并使用ternary operator切换它们:

private static Color DefaultBackColor = Color.Blue;
private static Color SelectedBackColor = Color.Red;

protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
    foreach (DataListItem dli in DataList1.Items)
    {
        dli.BackColor =
            dli == DataList1.SelectedItem
            ? SelectedBackColor;
            : DefaultBackColor;
        }
    }
}