我在ASP.net中有Gridview显示数据。根据数据,它会根据单元格的值更改颜色和文本。 当列不是模板字段时,这可以正常工作。
//WORKS WHEN IS NOT A TEMPLATE FIELD
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[2].Text == "1")
{
e.Row.Cells[2].Text = "IN";
e.Row.Cells[2].BackColor = Color.Blue;
e.Row.Cells[2].ForeColor = Color.White;
}
}
现在我将Column转换为Template字段,但没有任何作用。
//DOEST NOT WORK WHEN IS a TEMPLATE FIELD
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[2].Text == "1")
{
e.Row.Cells[2].Text = "IN";
e.Row.Cells[2].BackColor = Color.Blue;
e.Row.Cells[2].ForeColor = Color.White;
}
}
我得到颜色工作,但现在我需要将文本更改为以下内容。 IF statusID == 1然后显示IN,否则如果statusID == 2则显示OUT
<asp:TemplateField HeaderText="StatusID" SortExpression="StatusID">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue = '<%# Bind("StatusID") %>'>
<asp:ListItem Value="1">IN</asp:ListItem>
<asp:ListItem Value="2">OUT</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<%# Bind("StatusID") %>' ForeColor='<%# Convert.ToString(Eval("StatusID")) == "1" ? System.Drawing.Color.Green: Convert.ToString(Eval("StatusID")) == "2" ? System.Drawing.Color.Red: System.Drawing.Color.Purple%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
你们任何人都知道如何解决这个问题。提前谢谢。
答案 0 :(得分:7)
原因在模板列中不起作用,状态值为null。请尝试以下方法。
// In template column,
if (e.Row.RowType == DataControlRowType.DataRow)
{
var status = (Label)e.Row.FindControl("lblStatus");
if (status.Text == "1")
{
e.Row.Cells[2].Text = "IN";
e.Row.Cells[2].BackColor = Color.Blue;
e.Row.Cells[2].ForeColor = Color.White;
}
}
或者将DataItem转换为适当的对象并获取状态值。
// In template column,
if (e.Row.RowType == DataControlRowType.DataRow)
{
var obj = (MyObject)e.Row.DataItem;
if (obj.Status == 1)
{
e.Row.Cells[2].Text = "IN";
e.Row.Cells[2].BackColor = Color.Blue;
e.Row.Cells[2].ForeColor = Color.White;
}
}
答案 1 :(得分:2)
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl=(Label)e.Row.FindControl("lblStatus");
if (lbl.Text == "1")
{
lbl.Text = "IN";
e.Row.Cells[2].BackColor = Color.Blue;
e.Row.Cells[2].ForeColor = Color.White;
}
}
答案 2 :(得分:0)
我是vb programmar,这是一个示例代码。
If e.Row.RowType = DataControlRowType.DataRow Then
Dim abc As Label = TryCast(e.Row.FindControl("label1"), Label)
If abc.Text = "ADMIN" Then
e.Row.Cells(7).ForeColor = Drawing.Color.Blue
End If
End If
我真的希望它有效。
答案 3 :(得分:0)
使用ItemTemplate
并将Eval
环绕在您需要的任何HTML上,例如,更改颜色。
Text='<%# "Your HTML(use FONT COLOR=BLUE)" + Eval("HealthUnit") + "Close your HTML here" %>
as,here:
<asp:TemplateField HeaderText="Health Unit Website">
<ItemTemplate>
<asp:HyperLink runat="server"
NavigateUrl='<%# Eval("Website") %>'
tabindex="-1"
Target="_blank"
Text='<%# "<font color=blue><b>" +
Eval("HealthUnit") +
"</b></font>" %>'>
</asp:HyperLink>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" width="14%" />
</asp:TemplateField>