Gridview根据条件动态格式化
本文关键字:动态 格式化 条件 Gridview | 更新日期: 2023-09-27 18:15:44
我在RowDataBound上有这段代码,它交替了单元格的颜色,并在单元格上添加了一个onclick事件。数据动态地来自存储过程,因此gridview只有一个控件。ButtonField。我想让没有任何数据的单元格变成白色,我该怎么做呢?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
{
string back1 = "url('Images/GridBack1.jpg')";
string back2 = "url('Images/GridBack2.jpg')";
if (e.Row.RowType != DataControlRowType.DataRow)
return;
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TableCell Cell = e.Row.Cells[i];
// if both row and column are odd, color them black
// if both row and column are even, color them white
if (((e.Row.RowIndex % 2 == 1) && (i % 2 == 1)) ||
((e.Row.RowIndex % 2 == 0) && (i % 2 == 0)))
{
if (string.IsNullOrEmpty(e.Row.Cells[i].Text)) //Edit
{
e.Row.Cells[i].BackColor = Color.Blue;
e.Row.Cells[i].ForeColor = Color.White;
}
else
{
e.Row.Cells[i].Width = Unit.Pixel(450);
e.Row.Cells[i].Height = Unit.Pixel(67);
e.Row.Cells[i].Style.Add("background-image", back1);
//e.Row.Cells[i].Style.Add("width", "150px");
//e.Row.Cells[i].Style.Add("word-wrap","break-word");
e.Row.Cells[i].Attributes.Add("align", "center");
}
}
else
{
if (string.IsNullOrEmpty(e.Row.Cells[i].Text)) //Edit
{
e.Row.Cells[i].BackColor = Color.Blue;
e.Row.Cells[i].ForeColor = Color.White;
}
else
{
e.Row.Cells[i].Width = Unit.Pixel(450);
e.Row.Cells[i].Height = Unit.Pixel(67);
e.Row.Cells[i].Style.Add("background-image", back2);
//e.Row.Cells[i].Style.Add("width", "150px");
//e.Row.Cells[i].Style.Add("word-wrap", "break-word");
e.Row.Cells[i].Attributes.Add("align", "center");
}
}
string color = "#000000";
e.Row.Cells[0].Attributes.Add("Style", "background-color: " + color + ";");
e.Row.Cells[0].Width = Unit.Pixel(150);
e.Row.Cells[0].Height = Unit.Pixel(67);
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
// Add events to each editable cell
for (int columnIndex = 2; columnIndex < e.Row.Cells.Count; columnIndex++)
{
// Add the column index as the event argument parameter
string js = _jsSingle.Insert(_jsSingle.Length - 2, columnIndex.ToString());
// Add this javascript to the onclick Attribute of the cell
e.Row.Cells[columnIndex].Attributes["onclick"] = js;
// Add a cursor style to the cells
e.Row.Cells[columnIndex].Attributes["style"] += "cursor:pointer;cursor:hand;";
}
}
}
}
尝试为每个单元格分配白色,然后根据条件覆盖。
您需要使用string.IsNullOrEmpty()
if(string.IsNullOrEmpty(e.Row.Cells[i].Text))
{
e.Row.Cells[i].BackColor = Color.Blue;
e.Row.Cells[i].ForeColor = Color.White;
}
MSDN