ASP.NET更改文本和颜色的GridView细胞的模板字段 [英] ASP.NET Change Text and Color in Gridview cell in a Template Field
问题描述
我的GridView的ASP.net显示的数据。根据数据它改变取决于单元格的值的颜色和文本。
这工作得很好,当列不是一个模板领域。
I have Gridview in ASP.net that displays data. Depending on the data it changes color and text depending on the value of the cell. This works fine when a column is NOT a template field.
//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;
}
}
现在我转换列中的模板字段并没有什么工作。
Now I converted the Column in to a Template field and nothing works.
//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
I GOT THE COLOR WORKING, but now I need to change the Text to the following. IF statusID == 1 then display IN, else if statusID == 2 then display 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>
任何人都知道如何解决这个问题。先谢谢了。
Any of you know how to solve this issue. Thanks in advance.
推荐答案
原因模板列不工作的状态是值为空。请尝试以下方法。
The reason doesn't work in template column is status value is null. Try the following.
// 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到appropiate对象并获取状态值。
Or cast DataItem to appropiate object and get the status value.
<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.dataitem.aspx\">GridViewRow.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;
}
}
这篇关于ASP.NET更改文本和颜色的GridView细胞的模板字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!